系统流:
—System.out
—System.in
—System.err
这3个流是java.lang.System类中的静态成员(译者注:这3个变量均为final static常量),并且已经预先在JVM启动的时候初始化完成,你依然可以更改它们。只需要把一个新的InputStream设置给System.in或者一个新的OutputStream设置给System.out或者System.err,之后的数据都将会在新的流中进行读取、写入。
可以使用System.setIn(), System.setOut(), System.setErr()方法设置新的系统流。
替换System.out,代码:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
public class NewSystemOut {
public static void main(String[] args){
try {
OutputStream os = new FileOutputStream("C:\\Users\\wangz\\Desktop\\out.txt");
PrintStream ps = new PrintStream(os);
System.setOut(ps);
int i = 10;
while(true){
i--;
System.out.append("Hello world!!!\r\n");
if(i == 0)
break;
}
System.out.flush();
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
结果,out.txt
Hello world!!!
Hello world!!!
Hello world!!!
Hello world!!!
Hello world!!!
Hello world!!!
Hello world!!!
Hello world!!!
Hello world!!!
Hello world!!!
原文:http://ifeve.com/java-io-system-in-system-out-system-err/