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();
}
添加回答
舉報