Reputation: 1141
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
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
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
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