Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert fileoutputstream to a string

Tags:

java

I have a java program where I am writing to a file using OutputStream. Everything is working fine. Upon completion of the program, I see data in my file. However, I would like to see this data on the System.out as well.

How can I convert OutputStream to a String so that I can simply System.out.println(); it? I tried fos.toString() but that prints java.io.FileOutputStream@1ed2e55e

like image 566
birdy Avatar asked Oct 25 '25 02:10

birdy


1 Answers

Use a ByteArrayOutputStream and you can create a string from it. Assuming the 'stream' variable is a reference to your ByteArrayOutputStream in the following example, here's how you could do it...

System.out.println(new String(stream.toByteArray(), CharSet.defaultCharSet()));

EDIT: was missing a closing parenthesis above, fixed now

like image 163
Jim Avatar answered Oct 27 '25 14:10

Jim