简体   繁体   English

使用printwriter与System.out.print打印整数

[英]Printing an integer using printwriter vs System.out.print

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. 我正在尝试将控制台数组中的字节读取到控制台,如果使用PrintWriter对象,则屏幕上不会打印任何内容,但是使用System.out.println()可以正常工作。 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. 根据这个http://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html PrintWriter方法print(int i)打印一个整数,所以我很困惑。

The System.out variable is referencing an object of type PrintStream which wraps a BufferedOutputStream (at least in Oracle JDK 7). System.out变量引用包装了BufferedOutputStream PrintStream类型的对象(至少在Oracle JDK 7中)。 When you call one of the printX() or write() methods on PrintStream , it internally flushes the buffer of the underlying BufferedOutputStream . 当您在PrintStream上调用printX()write()方法之一时,它将在内部刷新基础BufferedOutputStream的缓冲区。

That doesn't happen with PrintWriter . 使用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. 或者,您可以创建一个将autoFlush属性设置为truePrintWriter ,该属性将在每次写入时刷新。

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

If you read this constructor's javadoc , it states 如果您阅读此构造函数的javadoc ,它将指出

  • autoFlush A boolean; autoFlush一个布尔值; if true, the println, printf, or format methods will flush the output buffer 如果为true,则println,printf或format方法将刷新输出缓冲区

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM