0

Hi everyone, I've been searching through these forums to find a way to transfer my program output [including the user's input] to a .txt file. The program basically gets the user's name and their choice of ingredients and then prints out a receipt of their order. Below I've attached what I've done using some of the answers I've seen on here. Whenever I come to run the program, I get a file named "output.txt" but nothing is in it. Do I need to be putting the code for file output somewhere else? Perhaps before all the methods to get the user's details and print order?

public static void main(String[] args){
        Pizza P1 = new Pizza();
        P1.Customer_details();
        P1.base_type();
        P1.sauce_type();
        P1.cheese_type();
        P1.select_toppings();
        P1.total_price();  
        P1.display_price();

        //Printing output to text file
        String fileName = "output.txt";
        final boolean append = true, autoflush = true;
        PrintStream printStream = null;
        try {
            printStream = new PrintStream(new FileOutputStream(fileName, append),  autoflush);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        System.setOut(printStream);
    }

}

Edited by George_23

3
Contributors
3
Replies
16
Views
7 Months
Discussion Span
Last Post by JamesCherrill
0

You need to execute the System.setOut(printStream); before you execute any statements that generate output. In other words all output goes to the default System.out until you call setOut. After that any new output goes to your file.

Edited by JamesCherrill

0

Hi,

The statement :

printStream = new PrintStream(new FileOutputStream(fileName, append),  autoflush);

Creates the file but does not write into it.
You must write in the file using : printStream.print()

More details

0

Hi Tarek
Wha you say is true, but OP wants to redirect his ordonary output - ie the stuff he prints to System.out
By using System.setOut he can set System.out to refer to his PrintStream, so normal propgram output will be written to that stream thereafter.
You can do the same with System.err

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.