从 ByteArrayOutputStream 创建文件

有人能解释一下,如果我只有一个 ByteArrayOutputStream,我怎样才能得到一个文件对象。如何从 ByteArrayOutputStream创建文件?

181507 次浏览

You can do it with using a FileOutputStream and the writeTo method.

ByteArrayOutputStream byteArrayOutputStream = getByteStreamMethod();
try(OutputStream outputStream = new FileOutputStream("thefilename")) {
byteArrayOutputStream.writeTo(outputStream);
}

Source: "Creating a file from ByteArrayOutputStream in Java." on Code Inventions

You can use a FileOutputStream for this.

FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("myFile"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();


// Put data in your baos


baos.writeTo(fos);
} catch(IOException ioe) {
// Handle exception here
ioe.printStackTrace();
} finally {
fos.close();
}