Sometimes, the file name string could be awkward especially when the file comes from the web. For example

 
http://www.gravatar.com/avatar/1e86128f2cb515febc94b63b33a8465a%3Fs%3D40%26r%3Dpg%26d%3Dhttp%253A%252F%252Fb-i.forbesimg.com%252Fassets%252Fimages%252Favatars%252Fgeneric_profile_image_40.jpg
 

If you try to save this file on the disk, Java throws an exception:

file not found

In Windows, those characters are invalid for a filename

 
\/:?*"<>|
 

Here is a solution in Java

 
filename = filename.replaceAll("[\\\\/:*?\"<>|]", "");
if(filename.length() == 0) filename = "validfilename";
 
String alternateName = filename;
int i = 0;
while(file_exists(filepath+alternateName)) {
    alternateName = i+filename;i++;
} 
 
SaveFile(alternateName);
 
 

The replaceAll will removes all invalid character and then check whether the file name already exists in target directory, if it exist, generate an alternative name by prefix a number to the name.