1 // Copyright (C) 2003 Adam Megacz <adam@ibex.org> all rights reserved.
3 // You may modify, copy, and redistribute this code under the terms of
4 // the GNU Library Public License version 2.1, with the exception of
5 // the portion of clause 6a after the semicolon (aka the "obnoxious
12 /** provides commands to urlencode and urldecode strings, making sure
13 * to escape sequences which have special meanings in filenames */
14 public class FileNameEncoder {
16 private static final char[] hex =
17 new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
19 public static String encode(String s) {
20 StringBuffer sb = new StringBuffer();
22 byte[] b = s.getBytes("UTF-8");
23 for(int i=0; i<b.length; i++) {
24 char c = (char)(b[i] & 0xff);
25 if (c == File.separatorChar || c < 32 || c > 126 || c == '%' || (i == 0 && c == '.'))
26 sb.append("%" + hex[(b[i] & 0xf0) >> 8] + hex[b[i] & 0xf]);
30 } catch (UnsupportedEncodingException uee) {
31 throw new Error("this should never happen; Java spec mandates UTF-8 support");
35 public static String decode(String s) {
36 StringBuffer sb = new StringBuffer();
37 byte[] b = new byte[s.length() * 2];
39 for(int i=0; i<s.length(); i++) {
41 if (c == '%') b[bytes++] = (byte)Integer.parseInt(("" + s.charAt(++i) + s.charAt(++i)), 16);
42 else b[bytes++] = (byte)c;
45 return new String(b, 0, bytes, "UTF-8");
46 } catch (UnsupportedEncodingException uee) {
47 throw new Error("this should never happen; Java spec mandates UTF-8 support");