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
Answer from Suresh Atta on Stack OverflowYou 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();
}
Videos
Scenario: I have a REST API endpoint built with Spring Boot. The endpoint is used to dynamically generate an excel file based off input parameters. When the file is done being generated, it returns the file as an InputStreamResource. The main goal is minimum memory usage.
I'm using fastexcel to create the excel file, and I'm flushing it to the OutputStream after every row is written. Right now, I am using a FileOutputStream to write to disk. When the excel file is done being generated, I read it back in using InputStreamResource and stream the response. My thought process is that a ByteArrayOutputStream keeps everything in memory even if I'm flushing the excel file after every row, so I used the FileOutputStream. Does my logic track here? Or am I unnecessarily slowing things down with expensive filesystem IO?
java.nio.file.Files.readAllBytes() can be of help in Java 7.
Read all the bytes from a file. The method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown.
Note that this method is intended for simple cases where it is convenient to read all bytes into a byte array. It is not intended for reading in large files.
The more conventional way would be to use a
FileInputStreamandread()the file to abyte[].Apache Commons IO has byte[] org.apache.commons.io.IOUtils.toByteArray(InputStream input) method.
Google's Guava got ByteStreams.toByteArray(InputStream) and Files.toByteArray(File).
Here's the old fashioned way to read from a file into a ByteArrayOutputStream.
public void getBytes(String fileName) throws FileNotFoundException,
IOException {
byte[] buffer = new byte[4096];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
fileName));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytes = 0;
while ((bytes = bis.read(buffer, 0, buffer.length)) > 0) {
baos.write(buffer, 0, bytes);
}
baos.close();
bis.close();
}