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

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++;

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.