Вопрос

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