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