Java File Name Sanitize sanitizeFileName(String s)

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

Description

Return a valid file name, replacing all invalid characters with '_'.

License

Open Source License

Parameter

Parameter Description
s Incoming string to be sanitized.

Return

A valid file name.

Declaration

public static String sanitizeFileName(String s) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2012 Firestar Software, Inc.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:/*from   www.j ava2s  .c  om*/
 *     Firestar Software, Inc. - initial API and implementation
 *
 * Author:
 *     Gabriel Oancea
 *
 *******************************************************************************/

public class Main {
    private static final String INVALID_FILE_NAME_CHARS = "\\|/:*?\"<>,'`; ";

    /**
     * Return a valid file name, replacing all invalid characters with '_'.
     * 
     * @param s Incoming string to be sanitized.
     * @return A valid file name.
     */
    public static String sanitizeFileName(String s) {
        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();
    }
}

Related

  1. sanitizeFilename(String fileName)
  2. sanitizeFilename(String name)
  3. sanitizeFileName(String name)
  4. sanitizeFilename(String name)
  5. sanitizeFileName(String name)
  6. sanitizeFilename(String toClean)
  7. sanitizeFilenameForWindows(String filename)
  8. sanitizeForFileName(final String orig)
  9. sanitizeToValidFilename(String name)