0

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??

Olimpiu POP
  • 5,001
  • 4
  • 34
  • 49
Sarah Jeffi
  • 53
  • 2
  • 10
  • does `df.displayCategorizedList();` print to stdout? Then you should probably move it behind `System.setOut()` – Andreas Fester Apr 05 '13 at 07:26
  • I am new in java , can you give me more hint please – Sarah Jeffi Apr 05 '13 at 07:26
  • This topic seems to have been dealt with fairly thoroughly [over here](http://stackoverflow.com/questions/1994255/how-to-write-console-output-to-a-txt-file). – Steven Apr 05 '13 at 07:27
  • @SaharSj He means that the output seems to be done before you call `setOut()`. Just move `df.displayCategorizedList();` below your try/catch block. – Axel Apr 05 '13 at 07:29

2 Answers2

5

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.

giorashc
  • 13,691
  • 3
  • 35
  • 71
0

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.

Olimpiu POP
  • 5,001
  • 4
  • 34
  • 49