Force a valid Windows filename

 /**
  * replace illegal characters in a filename with "_"
  * illegal characters : 
  *           : \ / * ? | < > 
  * @param name
  * @return
  */
  public static String sanitizeFilename(String name) {
    return name.replaceAll("[:\\\\/*?|<>]", "_");
  }

  public static void main(String args[]) throws Exception {

    String test = "invalid : file ? name.txt";
    System.out.println(test + " -> " + sanitizeFilename(test));
    /* output :
     * 
     *   invalid : file ? name. -> invalid _ file _ name.txt
     *   
     */    
  }  
}



If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2010
[ home ]