Java examples for java.lang:String Replace
This methods replaces invalid or reserved characters in a directory name.
/**//from w ww . j a va 2 s .c om * * Copyright (C) 2004-2008 FhG Fokus * * This file is part of the FhG Fokus UPnP stack - an open source UPnP implementation * with some additional features * * You can redistribute the FhG Fokus UPnP stack and/or modify it * under the terms of the GNU General Public License Version 3 as published by * the Free Software Foundation. * * For a license to use the FhG Fokus UPnP stack software under conditions * other than those described here, or to purchase support for this * software, please contact Fraunhofer FOKUS by e-mail at the following * addresses: * upnpstack@fokus.fraunhofer.de * * The FhG Fokus UPnP stack is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/> * or write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ import java.text.DecimalFormat; import java.util.List; import java.util.StringTokenizer; import java.util.Vector; public class Main{ public static void main(String[] argv){ String directoryName = "java2s.com"; System.out.println(escapeDirectoryName(directoryName)); } final static String VALID_DIRECTORY_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXZY0123456789-_.()"; /** * This methods replaces invalid or reserved characters in a directory name. This should be called when creating * directory names from arbitrary strings. * * @param directoryName * File name to convert * * @return A file name suitable for all operating systems that support % in filenames */ public static String escapeDirectoryName(String directoryName) { if (directoryName.length() == 0) { return ""; } StringBuffer nameBuffer = new StringBuffer( directoryName.length() * 2); try { byte[] nameData = StringHelper.stringToByteArray(directoryName); for (int i = 0; i < nameData.length; i++) { int ch = nameData[i] & 0xFF; // check for valid characters if (VALID_DIRECTORY_CHARS.indexOf(ch) >= 0) { nameBuffer.append((char) ch); } else { // invalid character, escape nameBuffer.append('%'); // force two digits if (ch < 0x10) { nameBuffer.append('0'); } nameBuffer.append(Integer.toHexString(ch)); } } return nameBuffer.toString(); } catch (Exception ex) { } return null; } /** Converts a string to a byte array */ public static byte[] stringToByteArray(String dataString) { if (dataString == null) { return null; } byte[] result = new byte[dataString.length()]; for (int i = 0; i < dataString.length(); i++) { result[i] = (byte) dataString.charAt(i); } return result; } }