Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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, but this isn't working for me (no log file shows up in any location on Mac OS X or Windows). From what I can tell, this is because I'm using a plain Java app without Java web start. So how can I do this with Java code that does not use Java web start? Ideally, I would like a solution that does not require modifying code.

like image 955
Thunderforge Avatar asked Sep 07 '13 03:09

Thunderforge


2 Answers

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.

like image 170
Katona Avatar answered Nov 01 '22 17:11

Katona


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 {
    System.setOut(new PrintStream(new FileOutputStream("home.txt")));
    System.out.println("hello");
}

This 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
like image 42
Sotirios Delimanolis Avatar answered Nov 01 '22 18:11

Sotirios Delimanolis