How Can I Pipe the Java Console Output to File Without Java Web Start?

前端 未结 4 855
暗喜
暗喜 2020-12-16 02:59

I am wanting to pipe the Java console output (generated by System.out.println and its ilk) to a file. I found an excellent solution here to enable Java tracing,

相关标签:
4条回答
  • 2020-12-16 03:04

    If you want to run the problem in the background, do this -

    nohup java -jar yourprogram.jar > log.txt 2>&1 &
    
    0 讨论(0)
  • 2020-12-16 03:06

    Is there any way that I can do it without modifying code? I'd like to do it for an application that is already compiled.

    If you want to do it without changing code, then your best option is this:

    $ java com.example.MyMainClass > filename
    
    0 讨论(0)
  • 2020-12-16 03:09

    If you launch it from command line, then you can use redirect stdout and stderr into file as follows:

    java -jar application.jar >file.txt  2>&1
    

    where you have to replace application.jar with the jar file of your application.

    0 讨论(0)
  • 2020-12-16 03:15

    You don't require Java web start to do any of this. Just set the System.out to a FileOutputStream.

    System.setOut(new PrintStream(new FileOutputStream(fileName)));
    

    where fileName is the full path to the file you want to pipe to.

    public static void main(String[] args) throws Exception {   //Read user input into the array
        System.setOut(new PrintStream(new FileOutputStream("home.txt")));
        System.out.println("hello");
    }
    

    Will write hello\n to a file named home.txt in the current working directory.

    If you can't modify code, on Windows 7, use command redirection.

    java YourMainClass > home.txt
    

    If you need to run a jar, you can use the -jar option of the java application launcher.

    java -jar /your/path.jar > /output/file/path.txt
    
    0 讨论(0)
提交回复
热议问题