byte []以Java文件

elc*_*ool 300 java arrays io inputstream file

使用Java:

我有一个byte[]代表文件.

如何将其写入文件(即.C:\myfile.pdf)

我知道它已经完成了InputStream,但我似乎无法解决它.

bma*_*ies 460

使用Apache Commons IO

FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray)
Run Code Online (Sandbox Code Playgroud)

或者,如果你坚持为自己做工作......

try (FileOutputStream fos = new FileOutputStream("pathname")) {
   fos.write(myByteArray);
   //fos.close(); There is no more need for this line since you had created the instance of "fos" inside the try. And this will automatically close the OutputStream
}
Run Code Online (Sandbox Code Playgroud)

  • @R.Bemrose嗯,它可能设法在悲惨的情况下清理资源. (28认同)
  • 如果写入失败,您将泄漏输出流.你应该总是使用`try {} finally {}`来确保适当的资源清理. (24认同)
  • 为什么在普通Java的2行中使用apache commons IO (4认同)
  • fos.close()语句是多余的,因为您正在使用try-with-resources自动关闭流,即使写入失败也是如此. (3认同)
  • 来自文档:注意:从 v1.3 开始,如果文件的父目录不存在,则会创建它们。 (2认同)

Sha*_*ley 173

没有任何库:

try (FileOutputStream stream = new FileOutputStream(path)) {
    stream.write(bytes);
}
Run Code Online (Sandbox Code Playgroud)

使用Google Guava:

Files.write(bytes, new File(path));
Run Code Online (Sandbox Code Playgroud)

使用Apache Commons:

FileUtils.writeByteArrayToFile(new File(path), bytes);
Run Code Online (Sandbox Code Playgroud)

所有这些策略都要求您在某些时候捕获IOException.

  • @pavan `path` 的字符集?FileOutputStream 文档没有提到这一点,因此这可能是特定于平台的。我猜大多数情况下都是UTF-8。`bytes` 按原样写入,不涉及字符集。 (2认同)

TBi*_*iek 107

另一种解决方案java.nio.file:

byte[] bytes = ...;
Path path = Paths.get("C:\\myfile.pdf");
Files.write(path, bytes);
Run Code Online (Sandbox Code Playgroud)

  • 我不认为 `C:\myfile.pdf` 无论如何都能在 Android 上运行...;) (3认同)
  • 字符集似乎无关紧要,因为我们正在写入字节,而不是字符 (3认同)

Eng*_*321 33

此外,自Java 7以来,使用java.nio.file.Files一行:

Files.write(new File(filePath).toPath(), data);
Run Code Online (Sandbox Code Playgroud)

数据是你的byte [],filePath是String.您还可以使用StandardOpenOptions类添加多个文件打开选项.使用try/catch添加throws或surround.

  • 您可以使用`Paths.get(filePath);`而不是`new File(filePath).toPath()` (5认同)

Voi*_*icu 19

Java 7开始,您可以使用try-with-resources语句来避免泄漏资源并使代码更易于阅读.更多关于这一点.

要将byteArray文件写入文件,您可以执行以下操作:

try (FileOutputStream fos = new FileOutputStream("fullPathToFile")) {
    fos.write(byteArray);
} catch (IOException ioe) {
    ioe.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)