如何将控制台输出保存到某个目录中的文本文件?

时间:2015-06-12 14:49:16

标签: java stream console

我想让控制台显示输出,但也将它作为日志保存在文本文件中。有没有办法做到这一点?我试过这样做:

PrintStream printStream = new PrintStream(new FileOutputStream(locations[0][0] + "-" + locations[0][1] + "-output.txt"));
System.setOut(printStream);

但它不再显示控制台中的输出,并将其保存在项目目录中。有办法做到这两点吗?

1 个答案:

答案 0 :(得分:1)

您需要使用写入两个目标流(文件和stdio)的流。例如,使用Apache's TeeOutputStream

// Directory to save log files in
File logDir = new File("/var/log/myapp");
// Name of log file
String logFileName = locations[0][0] + "-" + locations[0][1] + "-output.txt";
// Actual log file
File logFile = new File(logDir, logFileName);

// File stream
OutputStream fileStream = new FileOutputStream(logFile);
// Stdout
OutputStream stdioStream = System.out;
// A stream redirecting output to both supplied streams
OutputStream combinedStream = new TeeOutputStream(stdioStream, fileStream);
// Finally use the resulting stream
System.setOut(new PrintStream(combinedStream));

另一个替代方案(在JAVA范围之外)是使用* nix tee工具:

java -cp ... com.package.MyClass | tee /var/log/myapp/mylogfile.txt