Java File Name Sanitize sanitizeFileName(String filename)

Here you can find the source of sanitizeFileName(String filename)

Description

Given an input, return a sanitized form of the input suitable for use as a file/directory name

License

Open Source License

Parameter

Parameter Description
filename the filename to sanitize.

Return

a sanitized version of the input

Declaration

public static String sanitizeFileName(String filename) 

Method Source Code

//package com.java2s;
// License as published by the Free Software Foundation; either

public class Main {
    /**/*from ww w  .j  av a 2s.  co  m*/
     * list of characters not allowed in filenames
     */
    public static final char INVALID_CHARS[] = { '\\', '/', ':', '*', '?', '"', '<', '>', '|', '[', ']', '\'', ';',
            '=', ',' };
    private static final char SANITIZED_CHAR = '_';

    /**
     * Given an input, return a sanitized form of the input suitable for use as
     * a file/directory name
     *
     * @param filename the filename to sanitize.
     * @return a sanitized version of the input
     */
    public static String sanitizeFileName(String filename) {
        return sanitizeFileName(filename, SANITIZED_CHAR);
    }

    public static String sanitizeFileName(String filename, char substitute) {

        for (int i = 0; i < INVALID_CHARS.length; i++) {
            if (-1 != filename.indexOf(INVALID_CHARS[i])) {
                filename = filename.replace(INVALID_CHARS[i], substitute);
            }
        }

        return filename;
    }
}

Related

  1. sanitize(String fileName)
  2. sanitizeBlankNodeName(String filename)
  3. sanitizeFilename(String filename)
  4. sanitizeFilename(String fileName)
  5. sanitizeFileName(String filename)
  6. sanitizeFileName(String name)