Java Utililty Methods File Name Sanitize

List of utility methods to do File Name Sanitize

Description

The list of methods to do File Name Sanitize are organized into topic(s).

Method

StringsanitizeFileName(String s)
Return a valid file name, replacing all invalid characters with '_'.
if (s == null || s.length() <= 0)
    return s;
StringBuffer sb = new StringBuffer(s);
for (int i = 0; i < sb.length(); i++) {
    char c = sb.charAt(i);
    if (INVALID_FILE_NAME_CHARS.indexOf(c) >= 0)
        sb.setCharAt(i, '_');
return sb.toString();
StringsanitizeFilename(String toClean)
makes the string a more friendly filesystem path for java.
if (toClean == null)
    return toClean; 
String toReturn = toClean.replace('\\', '/');
return toReturn;
StringsanitizeFilenameForWindows(String filename)
sanitize Filename For Windows
String sanitized = filename;
for (String ic : ILLEGAL_FILENAME_CHARS) {
    sanitized = sanitized.replace(ic, "_");
return sanitized;
StringsanitizeForFileName(final String orig)
Converts a string into an other string that looks about as similar to the original as possible, while being save (and nice) to be used as a (part of a) file name.
return orig.replaceAll("[^_\\-.0-9a-zA-Z]", "_");
StringsanitizeToValidFilename(String name)
sanitize To Valid Filename
String[] invalidSymbols = new String[] { "\\", "/", ":", "*", "?", "\"", "<", ">", "|" };
String sanitizedName = name;
for (String currentSymbol : invalidSymbols) {
    sanitizedName = sanitizedName.replaceAll("[\\" + currentSymbol + "]", "_");
return sanitizedName;