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

4
  • does df.displayCategorizedList(); print to stdout? Then you should probably move it behind System.setOut() Commented Apr 5, 2013 at 7:26
  • I am new in java , can you give me more hint please Commented Apr 5, 2013 at 7:26
  • This topic seems to have been dealt with fairly thoroughly over here. Commented Apr 5, 2013 at 7:27
  • @SaharSj He means that the output seems to be done before you call setOut(). Just move df.displayCategorizedList(); below your try/catch block. Commented Apr 5, 2013 at 7:29

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

you set the o/p stream to file then save in c folder
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.