Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't pass System.out instance properly to FilterOutputStream

Tags:

java

stream

Why doesn't this code work, unless I uncomment the System.out.print(" "); line?

3 cases:

  • System.out.print(" "); after outprint.write(var); results in: h e l l o w o r l
  • System.out.print(" "); before outprint.write(var); results in: h e l l o w o r l d
  • without System.out.print(" "); nothing is displayed

To sum up, I do pass the System.out instance (which is a PrintStream) to the out attribute of the FilterOutputStream object (which takes an 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();
            }
        }
    }
}
like image 502
Stéphane Bruckert Avatar asked Dec 27 '22 02:12

Stéphane Bruckert


2 Answers

This is because you have to manually invoke outputstream.flush(); (instead of System.out.print())

like image 70
Andremoniy Avatar answered Apr 28 '23 00:04

Andremoniy


Whatever you added to the stream is being buffered but not being flushed. Without the line try flushing 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();
}
like image 23
Bhesh Gurung Avatar answered Apr 27 '23 22:04

Bhesh Gurung