Java中的字节数组转文件

404

使用Java:

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

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

我知道可以使用InputStream,但我似乎无法解决它。

12个回答

612

使用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
}

28
@R. Bemrose 嗯,它可能成功地清理了资源在悲伤的情况下。 - Tom Hawtin - tackline
2
从文档中:注意:从v1.3开始,如果不存在,文件的父目录将被创建。 - bmargulies
24
如果写入失败,你将会泄漏输出流。为确保资源得到正确清理,你应该总是使用 try {} finally {} - Steven Schlansker
8
由于您使用了try-with-resources,它会自动关闭流,即使写入失败,因此fos.close()语句是多余的。 - Tihomir Meščić
14
使用Apache Commons IO的原因是什么?使用普通Java代码只需要两行就可以实现同样的功能。 - GabrielBB
显示剩余2条评论

229

没有使用任何库:

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 异常。


在这种情况下,字符集怎么样? - Pavan
2
@pavan path 的字符集是什么?FileOutputStream 文档没有提到这一点,所以这可能是特定于平台的。我猜在绝大多数情况下它是 UTF-8。 bytes 会按原样写入,不涉及字符集。 - Alexey Nezhdanov

159

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

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

3
我认为C:\myfile.pdf在安卓上无法使用...;) - TBieniek
@TB 在这种情况下字符集怎么样? - Pavan
4
字符集似乎不相关,因为我们正在编写字节而不是字符。 - TBieniek
无论你说什么都是真的,我明白了我的错误。 - Pavan

47

自Java 7以来,可以使用java.nio.file.Files中的一行代码:

Files.write(new File(filePath).toPath(), data);

如果数据是byte[],文件路径是String,你可以使用StandardOpenOptions类添加多个文件打开选项。请添加throws或者用try/catch包围。


7
你可以使用 Paths.get(filePath); 替代 new File(filePath).toPath() - Tim Büthe
@Halil 我认为那不对。根据Javadocs,打开选项有一个可选的第三个参数,“如果没有选项,则此方法的工作方式就像存在CREATE、TRUNCATE_EXISTING和WRITE选项一样。换句话说,它会打开文件进行写入,如果文件不存在则创建文件,或者将现有的常规文件最初截断为0大小。” - Kevin Sadler

21

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

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

try (FileOutputStream fos = new FileOutputStream("fullPathToFile")) {
    fos.write(byteArray);
} catch (IOException ioe) {
    ioe.printStackTrace();
}

我尝试使用这个,但它会导致一些不是UTF-8字符的字节问题,所以如果你想写入单个字节来构建文件,我建议你小心使用。 - pdrum

4

尝试使用OutputStream或更具体地说是FileOutputStream


4

基本示例:

String fileName = "file.test";

BufferedOutputStream bs = null;

try {

    FileOutputStream fs = new FileOutputStream(new File(fileName));
    bs = new BufferedOutputStream(fs);
    bs.write(byte_array);
    bs.close();
    bs = null;

} catch (Exception e) {
    e.printStackTrace()
}

if (bs != null) try { bs.close(); } catch (Exception e) {}

2
File f = new File(fileName);    
byte[] fileContent = msg.getByteSequenceContent();    

Path path = Paths.get(f.getAbsolutePath());
try {
    Files.write(path, fileContent);
} catch (IOException ex) {
    Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
}

2

////////////////////////// 1] 将文件转换为字节数组 [] ///////////////////

Path path = Paths.get(p);
                    byte[] data = null;                         
                    try {
                        data = Files.readAllBytes(path);
                    } catch (IOException ex) {
                        Logger.getLogger(Agent1.class.getName()).log(Level.SEVERE, null, ex);
                    }

/////////////////////// 2] 字节数组转文件 ///////////////////////////

 File f = new File(fileName);
 byte[] fileContent = msg.getByteSequenceContent();
Path path = Paths.get(f.getAbsolutePath());
                            try {
                                Files.write(path, fileContent);
                            } catch (IOException ex) {
                                Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
                            }

谢谢您的回答。但是我对“fileName”有些困惑,我的意思是您正在保存什么类型的文件数据?请您能否解释一下? - SRam
1
嗨,SRam,这完全取决于您的应用程序为什么要进行转换以及您想要输出的格式是什么,我建议选择 .txt 格式(例如:myconvertedfilename.txt),但这又取决于您的选择。 - Piyush Rumao

1

我知道这可以用InputStream完成。

实际上,你会写入到一个文件输出中...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接