我想将标准输出保存到文件中。为此,我使用了
System.setOut(new PrintStream(new File("output-file.txt")));
现在控制台没有任何输出。
try {
System.setOut(new PrintStream(new File("output-file.txt")));
} catch (Exception e) {
e.printStackTrace();
}
尽管我使用 stdout 来填充文件,但是否有可能在控制台中显示 stdout?
最佳答案
您可以创建一个带有执行两种写入操作的 OutputStream
的 PrintWriter
。
final OutputStream stdOut = System.out;
try {
System.setOut(new PrintStream(new OutputStream() {
private PrintStream ps = new PrintStream(new File("output-file.txt"));
@Override
public void write(int b) throws IOException {
ps.write(b);
stdOut.write(b);
}
@Override
public void flush() throws IOException {
super.flush();
ps.flush();
stdOut.flush();
}
@Override
public void close() throws IOException {
super.close();
ps.close();
// stdOut.close(); // Normally not done
}
}));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Hello, world!");
关于java - 在文件和控制台中显示标准输出(使用 System.setOut(new PrintStream(new File ("output-file.txt")),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54126403/