Is there a way to make PrintWriter or OutputStreamWriter print immediately after .write method is invoked? I have autoFlush turned on for PrintWriter. Yet for both these classes, the contents get printed only when the writer is closed.
For what it’s worth, I am using Writers because I need to abstract over console output, file output, and string output.
Thanks!
Edit:
An SSCCE that shows the problem:
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
PrintWriter p = new PrintWriter(System.out, true);
Scanner read = new Scanner(System.in);
while (read.hasNextLine()) {
String input = read.nextLine();
if (input.equals("end"))
break;
p.write(input);
}
p.close();
}
}
/* Sample run: (first four lines are input)
cow
mow
pow
end
cowmowpow
*/
The documentation for the
autoFlushconstructor parameter says:Given that you’re not using any of those methods, it’s not entirely surprising that it’s not helping.
The simplest approach would be to just call
flush()manually after everywrite– that’s what you’re trying to achieve, after all. I don’t know of anything which will make a writer flush by default after every write.Of course, you could write your own wrapper class – the equivalent of
BufferedWriter, but with the opposite effect. It could delegate all methods to the wrapped writer, but then immediately callflush()afterwards.