gpt4 book ai didi

java - System.out 转字符串

转载 作者:行者123 更新时间:2023-12-02 09:59:42 25 4
gpt4 key购买 nike

我有一个通过 Windows 命令行运行的应用程序,我希望能够复制已发送到控制台的所有数据并将其附加到文件中以进行调试。每当发生异常时,都会将报告保存到文件系统,其中包括异常堆栈跟踪和完整控制台。

我无法将整个控制台重定向到我的文件,因为我需要能够从用户那里获取控制台输入。

System.out.toString() 不返回控制台,而是返回对象本身的字符串表示形式。

最佳答案

即使不是最好的主意,一种解决方案也可能是:

public static void main(String[] xxx) {
System.setOut(new DoublePrintStream(System.out, "/myfile.txt"));
System.setErr(new DoublePrintStream(System.err, "/errors.txt"));

System.out.println("this works");
try { throw new RuntimeException("oulala");} catch(Exception e) { e.printStackTrace(); }

//System.out.close(); // maybe required at the end of execution
}

class DoublePrintStream extends PrintStream {
private final OutputStream fos;

DoublePrintStream(OutputStream out, String filename){
super(out);

try {
fos = new FileOutputStream(new File(filename));
} catch (FileNotFoundException e) {
throw new AssertionError("cant create file", e);
}
}

@Override
public void write(byte[] buf, int off, int len) {
super.write(buf, off, len);

try {
fos.write(buf, off, len);
} catch (IOException e) {
throw new RuntimeException(e);
}
}

@Override
public void close() {
try {
fos.close();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
super.close();
}
}
}

这样你就可以在控制台中输出+在一个文件中,并将所有错误放在一个单独的文件中。

即使日志框架更好,该解决方案的优点是根本不需要更改代码。

PS:在多线程上下文中,还应该同步DoublePrintStream的方法

关于java - System.out 转字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55727744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com