WomenInTech
WomenInTech

Reputation: 1141

write output while loop of console to a text file in java

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

Upvotes: 0

Views: 2893

Answers (3)

Dangling Piyush
Dangling Piyush

Reputation: 3676

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.

Upvotes: -1

Brian Agnew
Brian Agnew

Reputation: 272397

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 ?

Upvotes: 2

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33544

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

  }

Upvotes: 3

Related Questions