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

标签 java stream console

我想保持控制台显示输出,但也将其作为日志保存在文本文件中。有什么办法可以做到这一点吗?我尝试这样做:

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/

相关文章:

java - 使用 Java 在 Excel 中打开文件

java - java串口异常

c++ - 为什么不继承ifstream

python - Azure Speech SDK 使用 python 从流中将语音转换为文本

mongodb - 无法访问 http ://localhost:28017 when enable auth for mongod

c++ - 运行存储在 `std::wstring` 中的控制台命令

java - 自定义声明未出现在 WSO2 API Manager 的用户配置文件中

java - Dagger2 模块 : how to obtain context to pass to the constructor of a class I want to provide

python - 将流分成具有相等计数的箱

javascript - 如何从函数名获取 javascript 的源代码