elc*_*ool 300 java arrays io inputstream file
使用Java:
我有一个byte[]代表文件.
如何将其写入文件(即.C:\myfile.pdf)
我知道它已经完成了InputStream,但我似乎无法解决它.
bma*_*ies 460
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)
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)
FileUtils.writeByteArrayToFile(new File(path), bytes);
Run Code Online (Sandbox Code Playgroud)
所有这些策略都要求您在某些时候捕获IOException.
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)
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.
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)
| 归档时间: |
|
| 查看次数: |
538628 次 |
| 最近记录: |