Java File Name Encode fileNameEncode(String str)

Here you can find the source of fileNameEncode(String str)

Description

This encodes a string so that it may be used as a file name, converting the illegal characters to their Unicode HEX values.

License

Open Source License

Parameter

Parameter Description
str the string to be encoded

Return

the encoded resulting filename-safe string

Declaration

public static String fileNameEncode(String str) 

Method Source Code

//package com.java2s;

public class Main {
    /** List of characters that are forbidden in file names (including "[]" used
     * for encoding) *//*from w  w w .j  av a2s. co  m*/
    private static final String BAD_CHARS = "[]<>|&#!:/\\*?$^@%={}`~\"'";

    /**
     * This encodes a string so that it may be used as a file name, converting the illegal
     * characters to their Unicode HEX values.
     * @param str the string to be encoded
     * @return the encoded resulting filename-safe string
     */
    public static String fileNameEncode(String str) {

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < str.length(); ++i) {
            char c = str.charAt(i);
            if (c < 32 || c > 126 || BAD_CHARS.indexOf(c) != -1) {
                sb.append("[").append(Integer.toHexString(c)).append("]");
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
}

Related

  1. fileNameEncode(String fileName)
  2. filenameEncode(String string)