Java tutorial
//package com.java2s; /* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Main { /** * Escapes a string so that it's safe for use as a file or directory name on at least FAT32 * filesystems. FAT32 is the most restrictive of all filesystems still commonly used today. * * <p>For simplicity, this only handles common characters known to be illegal on FAT32: * <, >, :, ", /, \, |, ?, and *. % is also escaped since it is used as the escape character. * Escaping is performed in a consistent way so that no collisions occur and * {@link #unescapeFileName(String)} can be used to retrieve the original file name. * * @param fileName File name to be escaped. * @return An escaped file name which will be safe for use on at least FAT32 filesystems. */ public static String escapeFileName(String fileName) { int length = fileName.length(); int charactersToEscapeCount = 0; for (int i = 0; i < length; i++) { if (shouldEscapeCharacter(fileName.charAt(i))) { charactersToEscapeCount++; } } if (charactersToEscapeCount == 0) { return fileName; } int i = 0; StringBuilder builder = new StringBuilder(length + charactersToEscapeCount * 2); while (charactersToEscapeCount > 0) { char c = fileName.charAt(i++); if (shouldEscapeCharacter(c)) { builder.append('%').append(Integer.toHexString(c)); charactersToEscapeCount--; } else { builder.append(c); } } if (i < length) { builder.append(fileName, i, length); } return builder.toString(); } private static boolean shouldEscapeCharacter(char c) { switch (c) { case '<': case '>': case ':': case '"': case '/': case '\\': case '|': case '?': case '*': case '%': return true; default: return false; } } }