System.out转换为字符串 [英] System.out to string
问题描述
我有一个通过Windows命令行运行的应用程序,我希望能够复制已发送到控制台的所有数据,并将其附加到文件中以进行调试.每当发生异常时,报告就会保存到文件系统中,其中包括异常堆栈跟踪和完整的控制台.
I have an application that runs through the windows command line, and I want to be able to copy all of the data that has been sent to the console and append it to a file for debugging purposes. Whenever an exception happens, a report is saved to the file system that includes the exception stack trace and the full console.
我无法将整个控制台重定向到我的文件,因为我需要能够从用户那里获取控制台输入.
I cannot redirect the entire console to my file because I need to be able to obtain console input from the user.
System.out.toString()不返回控制台,而是对象本身的字符串表示形式.
System.out.toString() doesn't return the console, but a string representation of the object itself.
推荐答案
即使不是最好的主意,一种解决方案可能是:
Even if not the best idea, one solution could be:
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();
}
}
}
因此您在控制台+中有一个文件输出,而所有错误都在一个单独的文件中.
so you have output in the console + in a file, and all errors in a separate file.
即使日志记录框架更好,该解决方案也具有根本不需要更改代码的优点.
Even if logging frameworks are way better, this solution has the advantage to require no code change at all.
PS:在多线程上下文中,您还应该同步 DoublePrintStream
PS: in a multithreaded context, you should also synchronize the methods of DoublePrintStream
这篇关于System.out转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!