如果想将java程序的控制台输出打印到文件,需要调用System类的setOut()方法,此方法接受一个PrintStream对象作为参数。
如下实例代码,将程序的标准输出重定向到文件流中。
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
/**
* Main.java
*
* @author outofmemory.cn
*/
public class Main {
/**
* 将System.out重定向到文件
*
*/
public void redirectSystemOut() {
try {
System.setOut(new PrintStream(new FileOutputStream("system_out.txt")));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
return;
}
System.out.println("This won't get displayed on the console, but sent to the file system_out.txt");
}
/**
* 启动程序
*
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().redirectSystemOut();
}
}