문제

I'm trying to read the bytes I have in an array to the console and if I use a PrintWriter object, nothing is printed to the screen, however, using System.out.println() works fine. Why?

Here is what my code looks like:

private static void readByteArray(byte[] bytes) {
   ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
   PrintWriter pw = new PrintWriter(System.out);

   int c;
   while((c = bais.read()) != -1) {
   pw.print(c);
}

That code doesn't work, but if I do this:

private static void readByteArray(byte[] bytes) {
   ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
   PrintWriter pw = new PrintWriter(System.out);

   int c;
   while((c = bais.read()) != -1) {
   System.out.println(c);
}

It prints.

What is the difference? According to this http://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html the PrintWriter method print(int i) prints an integer so I'm confused.

도움이 되었습니까?

해결책

The System.out variable is referencing an object of type PrintStream which wraps a BufferedOutputStream (at least in Oracle JDK 7). When you call one of the printX() or write() methods on PrintStream, it internally flushes the buffer of the underlying BufferedOutputStream.

That doesn't happen with PrintWriter. You have to do it yourself. Alternatively, you can create a PrintWriter with an autoFlush property set to true which will flush on each write.

PrintWriter pw = new PrintWriter(System.out, true);

If you read this constructor's javadoc, it states

  • autoFlush A boolean; if true, the println, printf, or format methods will flush the output buffer
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top