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
System.out.print(" "); nothing is displayedTo 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();
            }
        }
    }
}
                This is because you have to manually invoke outputstream.flush();  (instead of  System.out.print())
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();
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With