System.out是一个PrintStream,而PrintStream是一个OutputStream。PrintWriter有一个可以接受OutputStream做为参数的构造器,所以可以将System.out转换成PrintWriter:
PrintWriter writer=new PrintWriter(System.out,true);
writer.println("nihao"+" :wo 是否");
要使用有两个参数的PrintWriter的构造器,并将第二个参数设置为true,以便开启自动清空功能;否则,你可能得不到结果。
重定向标准I/O:将from.txt中的内容转存到to.txt文件中。
注意:setIn(InputStream)
setOut(PrintStream)
setErr(PrintStream)
可以对标准输入,标准输出,标准错误进行I/O重定向。
package com.wjy.multithread;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
public class ReDirect {
public static void main(String args[]) {
PrintStream console=System.out;
try {
PrintStream out=new PrintStream(new BufferedOutputStream(new FileOutputStream(new File("./file/to.txt"))));
BufferedInputStream in=new BufferedInputStream(new FileInputStream(new File("./file/from.txt")));
System.setIn(in);
System.setOut(out);
String s;
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
while((s=reader.readLine())!=null){
System.out.println(s);
}
out.close();
System.setOut(console);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}