1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
9 /** provides commands to urlencode and urldecode strings, making sure
10 * to escape sequences which have special meanings in filenames */
11 public class FileNameEncoder {
13 private static final char[] hex =
14 new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
16 public static String encode(String s) {
17 StringBuffer sb = new StringBuffer();
19 byte[] b = s.getBytes("UTF-8");
20 for(int i=0; i<b.length; i++) {
21 char c = (char)(b[i] & 0xff);
22 if (c == File.separatorChar || c < 32 || c > 126 || c == '%' || (i == 0 && c == '.'))
23 sb.append("%" + hex[(b[i] & 0xf0) >> 8] + hex[b[i] & 0xf]);
27 } catch (UnsupportedEncodingException uee) {
28 throw new Error("this should never happen; Java spec mandates UTF-8 support");
32 public static String decode(String s) {
33 StringBuffer sb = new StringBuffer();
34 byte[] b = new byte[s.length() * 2];
36 for(int i=0; i<s.length(); i++) {
38 if (c == '%') b[bytes++] = (byte)Integer.parseInt(("" + s.charAt(++i) + s.charAt(++i)), 16);
39 else b[bytes++] = (byte)c;
42 return new String(b, 0, bytes, "UTF-8");
43 } catch (UnsupportedEncodingException uee) {
44 throw new Error("this should never happen; Java spec mandates UTF-8 support");