Java File Name Clean cleanFileName(final String originalFileName)

Here you can find the source of cleanFileName(final String originalFileName)

Description

Replace all characters that could give file system problems with underscores.

License

Apache License

Parameter

Parameter Description
originalFileName the original file name.

Return

the clean file name that should be safe on the popular platforms.

Declaration

public static String cleanFileName(final String originalFileName) 

Method Source Code

//package com.java2s;
/**//from  ww  w.  j  a  va 2  s  .  c o  m
 * Copyright 2014 VU University Medical Center.
 * Licensed under the Apache License version 2.0 (see http://www.apache.org/licenses/LICENSE-2.0.html).
 */

public class Main {
    /**
     * Replace all characters that could give file system problems with underscores.
     *
     * Inspired by http://stackoverflow.com/a/5626340/1694043 and sun.nio.fs.WindowsPathParser.isInvalidPathChar.
     *
     * @param originalFileName the original file name.
     * @return the clean file name that should be safe on the popular platforms.
     */
    public static String cleanFileName(final String originalFileName) {
        // See https://en.wikipedia.org/wiki/ASCII#ASCII_control_code_chart for information on ASCII control characters.
        final int controlCharactersLimit = 32;
        final int ruboutCharacter = 127;
        final StringBuilder cleanName = new StringBuilder();
        for (final char character : originalFileName.toCharArray()) {
            final boolean controlCharacter = character < controlCharactersLimit || character == ruboutCharacter;
            cleanName.append(!controlCharacter && "\\/<>:\"|?*".indexOf(character) == -1 ? character : "_");
        }
        return cleanName.toString();
    }
}

Related

  1. cleanFileName(final String value)
  2. cleanFileName(String arg)
  3. cleanFileName(String badFileName)
  4. cleanFilename(String filename)