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

        //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) {


Recommended Answers

All 3 Replies

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.


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, learning, and sharing knowledge.