3 回答

TA贡献1780条经验 获得超5个赞
使用Apache Commons IO
FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray)
或者,如果您坚持要自己做...
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
}

TA贡献1827条经验 获得超9个赞
没有任何库:
try (FileOutputStream stream = new FileOutputStream(path)) {
stream.write(bytes);
}
使用Google Guava:
Files.write(bytes, new File(path));
使用Apache Commons:
FileUtils.writeByteArrayToFile(new File(path), bytes);
所有这些策略都要求您在某个时刻也捕获IOException。

TA贡献1777条经验 获得超3个赞
从Java 7开始,您可以使用try-with-resources语句来避免资源泄漏,并使代码更易于阅读。在这里更多。
要将您的内容写入byteArray文件,您可以执行以下操作:
try (FileOutputStream fos = new FileOutputStream("fullPathToFile")) {
fos.write(byteArray);
} catch (IOException ioe) {
ioe.printStackTrace();
}
添加回答
举报