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);
    }

}

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.

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.