1 16 17 package javax.xml.transform.stream; 18 19 class FilePathToURI { 20 21 private static boolean gNeedEscaping[] = new boolean[128]; 23 private static char gAfterEscaping1[] = new char[128]; 25 private static char gAfterEscaping2[] = new char[128]; 27 private static char[] gHexChs = {'0', '1', '2', '3', '4', '5', '6', '7', 28 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; 29 static { 31 for (int i = 0; i <= 0x1f; i++) { 32 gNeedEscaping[i] = true; 33 gAfterEscaping1[i] = gHexChs[i >> 4]; 34 gAfterEscaping2[i] = gHexChs[i & 0xf]; 35 } 36 gNeedEscaping[0x7f] = true; 37 gAfterEscaping1[0x7f] = '7'; 38 gAfterEscaping2[0x7f] = 'F'; 39 char[] escChs = {' ', '<', '>', '#', '%', '"', '{', '}', 40 '|', '\\', '^', '~', '[', ']', '`'}; 41 int len = escChs.length; 42 char ch; 43 for (int i = 0; i < len; i++) { 44 ch = escChs[i]; 45 gNeedEscaping[ch] = true; 46 gAfterEscaping1[ch] = gHexChs[ch >> 4]; 47 gAfterEscaping2[ch] = gHexChs[ch & 0xf]; 48 } 49 } 50 51 public static String filepath2URI(String path){ 55 if (path == null) 57 return null; 58 59 char separator = java.io.File.separatorChar; 60 path = path.replace(separator, '/'); 61 62 int len = path.length(), ch; 63 StringBuffer buffer = new StringBuffer (len*3); 64 buffer.append("file://"); 65 if (len >= 2 && path.charAt(1) == ':') { 67 ch = Character.toUpperCase(path.charAt(0)); 68 if (ch >= 'A' && ch <= 'Z') { 69 buffer.append('/'); 70 } 71 } 72 73 int i = 0; 75 for (; i < len; i++) { 76 ch = path.charAt(i); 77 if (ch >= 128) 79 break; 80 if (gNeedEscaping[ch]) { 81 buffer.append('%'); 82 buffer.append(gAfterEscaping1[ch]); 83 buffer.append(gAfterEscaping2[ch]); 84 } 86 else { 87 buffer.append((char)ch); 88 } 89 } 90 91 if (i < len) { 93 byte[] bytes = null; 95 byte b; 96 try { 97 bytes = path.substring(i).getBytes("UTF-8"); 98 } catch (java.io.UnsupportedEncodingException e) { 99 return path; 101 } 102 len = bytes.length; 103 104 for (i = 0; i < len; i++) { 106 b = bytes[i]; 107 if (b < 0) { 109 ch = b + 256; 110 buffer.append('%'); 111 buffer.append(gHexChs[ch >> 4]); 112 buffer.append(gHexChs[ch & 0xf]); 113 } 114 else if (gNeedEscaping[b]) { 115 buffer.append('%'); 116 buffer.append(gAfterEscaping1[b]); 117 buffer.append(gAfterEscaping2[b]); 118 } 119 else { 120 buffer.append((char)b); 121 } 122 } 123 } 124 125 return buffer.toString(); 126 } 127 128 } | Popular Tags |