Java examples for java.io:File Name
Replaces characters that are illegal in filenames to underscores
public class Main { public static void main(String[] argv) { String path = "$%^&*()java2s.com"; System.out.println(safePathString(path)); }/*from ww w .j a va2s.c o m*/ /** * Replaces characters that are illegal in filenames to underscores ("_"). * <p> * * @param path * A string to be used in a file path or file name * @return The input string with illegal characters converted to an underscore. * The following characters are replaced: : % / \ ; $ > < * . ? " * | ! @ */ public static String safePathString(String path) { if (path == null) return "null"; StringBuilder b = new StringBuilder(); int cnt = path.length(); for (int i = 0; i < cnt; i++) { char c = path.charAt(i); if (c == ':' || c == '%' || c == '/' || c == '\\' || c == ';' || c == '$' || c == '>' || c == '<' || c == '*' || c == '.' || c == '?' || c == '"' || c == '|' || c == '!' || c == '@') { b.append('_'); } else { b.append((char) c); } } return b.toString(); } }