0

I am new to Java and I am stuck at this part :

I am trying to output the console output into a text file using JAVA . But the problem is I have a While loop running and my code writes the output to the file but deletes the previous one . I want to append the while loop output to file .

Any help is appreciated . Thanks In advance :)

PrintStream out = new PrintStream(new FileOutputStream("output.txt"));

System.setOut(out);

1
  • Just open the file once instead of every time through the loop. Commented Aug 13, 2012 at 11:19

3 Answers 3

3

You need to append the new data to the previous data in the file, try this...

try{
    File f = new File("d:\\t.txt");
    FileWriter fw = new FileWriter(f,true);    // true is for append
    BufferedWriter bw = new BufferedWriter(fw);

    bw.append(Your_data);
  }catch(Exception ex){

       ex.printStackTrace();

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

Comments

2

You should perform the redirection once, and before you do anything else. i.e. before you enter your loop.

Note (also) that your shell can redirect to a file, and that might be preferable to changing the destination of System.out. That's feasible but perhaps unexpected for someone who's going to debug your code in the future and wonder where their output is going...

Or perhaps consider a logging framework ?

Comments

-1

Do it like this:

  FileOutputStream fout=new FileOutputStream("output.txt",true);
  while(condition)
   {
      PrintStream out = new PrintStream(new FileOutputStream("output.txt"));

       System.setOut(out);

   }

where second argument to FileOutputStream will open it in appendable mode.

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.