I\'m receiving a string from an external process. I want to use that String to make a filename, and then write to that file. Here\'s my code snippet to do this:
Here's what I use:
public String sanitizeFilename(String inputName) {
return inputName.replaceAll("[^a-zA-Z0-9-_\\.]", "_");
}
What this does is is replace every character which is not a letter, number, underscore or dot with an underscore, using regex.
This means that something like "How to convert £ to $" will become "How_to_convert___to__". Admittedly, this result is not very user-friendly, but it is safe and the resulting directory /file names are guaranteed to work everywhere. In my case, the result is not shown to the user, and is thus not a problem, but you may want to alter the regex to be more permissive.
Worth noting that another problem I encountered was that I would sometimes get identical names (since it's based on user input), so you should be aware of that, since you can't have multiple directories / files with the same name in a single directory. I just prepended the current time and date, and a short random string to avoid that. (an actual random string, not a hash of the filename, since identical filenames will result in identical hashes)
Also, you may need to truncate or otherwise shorten the resulting string, since it may exceed the 255 character limit some systems have.