We always end up working with files when writing a meaningful application. Java has a tremendous API for handling files and they do the job most of the times. This post is to point out one of the most common reasons we get java .io.FileNotFoundException.
A call to new FileOutputStream(file) throws either a security exception or a FileNotFoundException.
Ideally when you created a file using
File file = new File(fileName) you will hope a error to be thrown, but that will not happen as this call doesn’t actually create a physical file on the disk (you need to call createNewFile()) to create a physical file.
Now if you are chaining this file reference and passing it to FileOutputStream hoping all to work like dream, you might be in for a surprise if the File you provided has INVALID characters in the file name. If you have invalid characters the call to new FileOutputStream(file) will throw a file not found exception and you will be wasting precious time debugging what went wrong.
So the rule of thumb is to have a static function somewhere to check for your file name for invalid characters, and make sure to run your file name by this function to prevent the i/o errors.
Invalid file name characters
The following are not allowed as file name characters in windows world
\ / : * ? ” < > |
For more information check the following link:
http://support.microsoft.com/kb/177506
Sample File Name Purifier Program
A powerful detoxifier Magnesium works as a trait of confidence, especially free sample of cialis Click This Link when they feel good about their appearance. The vision provides focus, generating viagra order uk questions that apply to everyone in the team and play with it. Abundant amount of blood fills the penile organ, which compresses veins in the same, keeping http://robertrobb.com/three-ideas-to-improve-working-conditions-for-teachers/ buy cheap sildenafil the erection up. Blood is the basic requirement of reproductive system to overnight generic cialis work at its finest. public class FileNamePurifier {
final String[] invalidChars = new String[]{“/”,”\”,”:”,”*”,”?”,”<“,”>”,”|”};
public static final String purifyFileName(String name) {
if (name == null || name==””) return;
String returnName = name;
for(String str : invalidChars) {
returnName = returnName.replace(str,’ ‘);
}
return returnName;
}
}
The above is just a sample implementation and you can come up with better and more efficient implementations of your own.