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:
String s = ... // comes from external source
File currentFile = new File(System.getProperty("user.home"), s);
PrintWriter currentWriter = new PrintWriter(currentFile);
If s contains an invalid character, such as '/' in a Unix-based OS, then a java.io.FileNotFoundException is (rightly) thrown.
How can I safely encode the String so that it can be used as a filename?
Edit: What I'm hoping for is an API call that does this for me.
I can do this:
String s = ... // comes from external source
File currentFile = new File(System.getProperty("user.home"), URLEncoder.encode(s, "UTF-8"));
PrintWriter currentWriter = new PrintWriter(currentFile);
But I'm not sure whether URLEncoder it is reliable for this purpose.