Sarah Jeffi
Sarah Jeffi

Reputation: 53

Writing output from console in java to text file

I'd like to show my Console's output in a text file.

public static void main(String [ ] args){
    DataFilter df = new DataFilter();   
    df.displayCategorizedList();
    PrintStream out;
    try {
        out = new PrintStream(new FileOutputStream("C:\\test1.txt", true));
        System.setOut(out);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

I get my result correctly on the screen but not result in the textfile ? the test file is genereted but it is empty??

Upvotes: 0

Views: 5233

Answers (2)

Olimpiu POP
Olimpiu POP

Reputation: 5067

I would suggest the following approach:

public static void main(String [ ] args){
    DataFilter df = new DataFilter();   
    try (PrintStream out = new PrintStream(new FileOutputStream("d:\\file.txt", true))) {
          System.setOut(out);
          df.displayCategorizedList();
    } catch (FileNotFoundException e) {
        System.err.println(String.format("An error %s occurred!", e.getMessage()));
    }
}

This is using the JDK 7 try-with-resources feature - meaning that it deals with exceptions (like FileNotFoundException) that you have and it also closes the resources (instead of the finally block).

If you cannot use JDK 7, use one of the approaches suggested in the other responses.

Upvotes: 0

giorashc
giorashc

Reputation: 13713

You should print to "console" after you have set the system output stream into a file.

    DataFilter df = new DataFilter();   
    PrintStream out;
    try {
        out = new PrintStream(new FileOutputStream("C:\\test1.txt", true));
        System.setOut(out);
        df.displayCategorizedList();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (out != null)
            out.close();
    }

Also use a finally block to always close the stream otherwise data might not be flushed to the file.

Upvotes: 5

Related Questions