System.out to string [duplicate]

旧城冷巷雨未停 提交于 2021-02-11 14:05:34

问题


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() doesn't return the console, but a string representation of the object itself.


回答1:


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: in a multithreaded context, you should also synchronize the methods of DoublePrintStream




回答2:


You can use this format to get console output to a text file if you are using CMD

javac {Programe_name}.java & java {Programe_name} > {Output_file_name>}

for example, if java programme is World.java

javac World.java & java World > out.txt



来源:https://stackoverflow.com/questions/55727744/system-out-to-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!