4

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

6
  • Just pass what ever data you pass to the OutputStream to write to the file to System.out.println() Commented Sep 12, 2013 at 20:08
  • Or after you are done writing to the file open a FileInputStream to read from the file what you have written to it - then use a BufferedReader to read it line by line and print it. This only makes sense if you want to see that your data was written correctly. Commented Sep 12, 2013 at 20:10
  • What inixsoftware said, or if the file isn't too big to read at once you could just print this out new String(Files.readAllBytes(Paths.get("file.txt")), "UTF-8"). Commented Sep 12, 2013 at 20:10
  • I am writing to the fos like this in a loop: fos.write((byte) mybyte) however, when I do the same to String s = (byte) mybyte i get errors Commented Sep 12, 2013 at 20:13
  • Either do System.out.print((char) mybyte); or sb.append((char) mybyte);. Commented Sep 12, 2013 at 20:21

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

you forget ) -> System.out.println(new String(stream.toByteArray(), CharSet.defaultCharSet()));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.