I was reading similar topic to mine at How to append text to an existing file in Java and have tried solutions there, unfortunately non of them answer my specific case.
I will be creating a lot of changes to a file so I thought that I will create method which will return PrintWriter
object on which I could do changes by executing writer.prinln("text");
private static PrintWriter WriteToFile() {
PrintWriter out = null;
BufferedWriter bw = null;
FileWriter fw = null;
try{
fw = new FileWriter("smrud.txt", true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
// out.println("the text");
return out;
}
catch( IOException e ){
return null;
}
finally{
try{
if( out != null ){
out.close(); // Will close bw and fw too
}
else if( bw != null ){
bw.close(); // Will close fw too
}
else if( fw != null ){
fw.close();
}
else{
// Oh boy did it fail hard! :3
}
}
catch( IOException e ){
// Closing the file writers failed for some obscure reason
}
}
}
So in my main method I'm calling this method
PrintWriter writer = WriteToFile();
Then I'm making changes
writer.println("the text2");
and I'm closing writer to save changes to disk:
writer.close();
Unfortunately I don't see any changes. When I put changes inside WriteToFile()
method then I see the changes:
private static void WriteToFile() {
PrintWriter out = null;
BufferedWriter bw = null;
FileWriter fw = null;
try{
fw = new FileWriter("smrud.txt", true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
out.println("the text");
}
catch( IOException e ){
// File writing/opening failed at some stage.
}
finally{
try{
if( out != null ){
out.close(); // Will close bw and fw too
}
else if( bw != null ){
bw.close(); // Will close fw too
}
else if( fw != null ){
fw.close();
}
else{
// Oh boy did it fail hard! :3
}
}
catch( IOException e ){
// Closing the file writers failed for some obscure reason
}
}
}
But this method open FileWriter
, BufferedWriter
and PrintWriter
every time it will be executed and I wanted to avoid that by returning PrintWriter
to main method and then executing writer.println("text");
and after some time close it by writer.close();
but this don't work.
Any suggestions will be appreciated.