Reputation: 915
I have legacy code which uses BufferedWriter to create a file in the file system.
The problem is that when there is some verification error in program it creates an empty file. It should not create the file at all when there is an verification error, but the error is detected only when data is written to it (verification). PFB the example code:
//Legacy code
File file1= new File(<path to directory>);
BufferedWriter dBufferedWriter = new BufferedWriter(new FileWriter(file1));
//Code that can have error and this repeats in loop
String str = "some string or null if error occurs";
if(validate(str)){
dBufferedWriter.write(str);
}
//Later at end
dBufferedWriter.close();
Is there a way to delay creating a file when it's not needed?
Upvotes: 0
Views: 863
Reputation: 310883
So the legacy code shouldn't create the file if it isn't going to be needed. So fix that.
String str = "some string or null if error occurs";
if(validate(str)){
File file1= new File(<path to directory>);
BufferedWriter writer1 = new BufferedWriter(new FileWriter(file1));
dBufferedWriter.write(str);
dBufferedWriter.close();
}
... assuming dBufferedWriter
and writer1
are the same thing.
Upvotes: 1
Reputation: 14015
When you create new FileWriter
it creates new file if this file does not exists. If you don't need any file in case of exception, you can use try{...}finally{...}
:
File file = new File(<path to directory>);
BufferedWriter dBufferedWriter = new BufferedWriter(new FileWriter(file));
try{
// some code where you can get exception
String str = "some string or null if error occurs";
dBufferedWriter.write(str);
}finally{
dBufferedWriter.close();
if(file.length()==0) file.delete();
}
By the way, it is a good practice to use finally
for close resource, even if you don't need to check file length.
Sure, if you can change legacy code's order, make it so, that the file will be created after verification code. In case of exception code after verification loop will not be reached:
// some code where you can get exception
Writer fileWriter = new FileWriter(new File(<path to directory>));
String str = "some string or null if error occurs";
dBufferedWriter.write(str);
dBufferedWriter.close();
Upvotes: 1