为了账号安全,请及时绑定邮箱和手机立即绑定

用Java归档的byte []

用Java归档的byte []

青春有我 2019-10-25 09:57:36
使用Java:我有一个byte[]代表文件的文件。如何将此写入文件(即C:\myfile.pdf)我知道它已经用InputStream完成了,但是我似乎无法解决。
查看完整描述

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

}


查看完整回答
反对 回复 2019-10-25
?
素胚勾勒不出你

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。


查看完整回答
反对 回复 2019-10-25
?
慕森王

TA贡献1777条经验 获得超3个赞

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


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


try (FileOutputStream fos = new FileOutputStream("fullPathToFile")) {

    fos.write(byteArray);

} catch (IOException ioe) {

    ioe.printStackTrace();

}


查看完整回答
反对 回复 2019-10-25
  • 3 回答
  • 0 关注
  • 704 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信