Cannot pass instance of System.out properly FilterOutputStream

Why this code does not work if I do not uncomment the line System.out.print(" "); ?

3 cases:

  • System.out.print(" "); after outprint.write(var); results in: helloworl
  • System.out.print(" "); before outprint.write(var); leads to: helloworld
  • without System.out.print(" "); nothing is displayed

To summarize, I pass an instance of System.out (which is PrintStream ) to the out attribute of the FilterOutputStream object (which accepts OutputStream ).


 import java.io.FilterOutputStream; import java.io.IOException; public class CodeCesar { public static void main(String[] args) { FilterOutputStream outputstream = new FilterOutputStream(System.out); String line = "hello world"; char[] lst_char = line.toCharArray(); for (char var : lst_char) { try { outputstream.write(var); System.out.print(" "); <--------- THIS LINE } catch (IOException e) { e.printStackTrace(); } } } } 
+4
source share
3 answers

This is because you must manually call outputstream.flush(); (instead of System.out.print() )

+7
source

Everything that you add to the stream is buffered but not cleared. Without a line, try clearing the output stream.

 try { for (char var : lst_char) { outputstream.write(var); } outputstream.flush(); //flush it once you are done writing } catch (IOException e) { e.printStackTrace(); } 
+3
source

Here is the corrected code for you. use flash ()

 public class CodeCesar { FilterOutputStream outputstream = new FilterOutputStream(System.out); String line = "hello world"; char[] lst_char = line.toCharArray(); for (char var : lst_char) { try { System.out.print(" "); outputstream.write(var); outputstream.flush(); } catch (IOException e) { e.printStackTrace(); } } } } 
0
source

Source: https://habr.com/ru/post/1485051/


All Articles