我想保持控制台显示输出,但也将其作为日志保存在文本文件中。有什么办法可以做到这一点吗?我尝试这样做:
PrintStream printStream = new PrintStream(new FileOutputStream(locations[0][0] + "-" + locations[0][1] + "-output.txt"));
System.setOut(printStream);
但它不再在控制台中显示输出,而是将其保存在项目目录中。有没有办法两全其美?
最佳答案
您需要使用一个写入两个目标流(文件和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
关于java - 如何将控制台输出保存到某个目录中的文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30806011/