Can someone explain how I can get a file object if I have only a ByteArrayOutputStream
. How to create a file from a ByteArrayOutputStream
?
Asked
Active
Viewed 1.5e+01k times
81
Andrew Thompson
- 163,965
- 36
- 203
- 405
Al Phaba
- 5,847
- 11
- 43
- 70
2 Answers
147
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
deb_
- 168
- 12
Suresh Atta
- 114,879
- 36
- 179
- 284
-
1@MarkusMikkolainen yeah ..obviously :) – Suresh Atta Jul 05 '13 at 12:10
-
9Or use java 7 try with resources statement to completely get rid off finally block;) http://stackoverflow.com/questions/2016299/does-java-have-a-using-statement – dimuthu May 05 '15 at 06:19
-
bro what if i dont have "thefilename" , insted i have byte[] stream of that excel, then what is the way? – Danish Jun 23 '20 at 10:40
26
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();
}
-
10Your code won't work with `fos` in `try` block. Also, `new File()` is not required. – Ludovic Guillaume Apr 02 '14 at 09:07
-
It's a good thing he added "new File()". It's easier for the reader to know there's a File constructor available. – Buffalo Sep 14 '15 at 06:37
-
-
Can be improved with fos inside try-with-resources () and dropping the finally – vikingsteve Jan 02 '17 at 14:29