问题描述
在阅读Java I / O时,我意识到有两种方法可以写入标准输出。
While reading about Java I/O, i realized that there are two ways through which i can write to the standard output.
以下是使用这两种技巧的代码段
Following is the snippet that uses both the techniques
import java.io.*;
public class ConsoleIO {
public static void main(String[] args) {
System.out.println("Method 1");
PrintWriter writer = new PrintWriter(System.out);
writer.println("Method 2");
writer.flush();
writer.close();
}
}
使用其中一个是否有任何性能优势?
Are there any performance benefits of using one over the other?
推荐答案
一个快速的Google在Coderanch上发布了一个有用的帖子。
A quick Google revealed a thread on Coderanch which was useful.
还有其他几种方法可以进行控制台编写,但除了编写较少的代码之外,使用其中一种方法似乎没有任何实际好处,并且创建新的PrintWriter对象将占用更多内存(最终)。
There are several other ways of doing console writing but there seems to be no real benefit of using one or the other apart from less code to write and that the creation of a new PrintWriter object will take up more memory (eventually).
PrintWriter可以写入除控制台之外的其他来源,它可以写入HttpResponse,例如System.out.println只写入控制台。
PrintWriter can write to other sources than just the console, it can write to an HttpResponse for example whilst System.out.println only writes to console.
这篇关于使用System.out和PrintWriter写入控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!