Makes a given filename safe by replacing special characters like slashes "/" and "\" with dashes "-". - Android java.io

Android examples for java.io:File Name

Description

Makes a given filename safe by replacing special characters like slashes "/" and "\" with dashes "-".

Demo Code

public class Main {

  private static final String[] FILE_SYSTEM_UNSAFE = { "/", "\\", "..", ":", "\"", "?", "*", "<", ">" };

  /**/*from w w  w  .  j  ava2s  .co m*/
   * Makes a given filename safe by replacing special characters like slashes ("/"
   * and "\") with dashes ("-").
   *
   * @param filename
   *          The filename in question.
   * @return The filename with special characters replaced by hyphens.
   */
   static String fileSystemSafe(String filename) {
    if (filename == null || filename.trim().length() == 0) {
      return "unnamed";
    }

    for (String s : FILE_SYSTEM_UNSAFE) {
      filename = filename.replace(s, "-");
    }
    return filename;
  }

}

Related Tutorials