1 package com.thaiopensource.util; 2 3 import java.net.URL ; 4 import java.net.MalformedURLException ; 5 import java.io.File ; 6 7 public class UriOrFile { 8 private UriOrFile() { 9 } 10 11 public static String toUri(String uriOrFile) { 12 if (!hasScheme(uriOrFile)) { 13 try { 14 return fileToUri(uriOrFile); 15 } 16 catch (MalformedURLException e) { } 17 } 18 return uriOrFile; 19 } 20 21 private static boolean hasScheme(String str) { 22 int len = str.length(); 23 if (len == 0) 24 return false; 25 if (!isAlpha(str.charAt(0))) 26 return false; 27 for (int i = 1; i < len; i++) { 28 char c = str.charAt(i); 29 switch (c) { 30 case ':': 31 return i == 1 ? false : true; 33 case '+': 34 case '-': 35 break; 36 default: 37 if (!isAlnum(c)) 38 return false; 39 break; 40 } 41 } 42 return false; 43 } 44 45 private static boolean isAlpha(char c) { 46 return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'); 47 } 48 49 private static boolean isAlnum(char c) { 50 return isAlpha(c) || ('0' <= c && c <= '9'); 51 } 52 53 public static String fileToUri(String file) throws MalformedURLException { 54 return fileToUri(new File (file)); 55 } 56 57 public static String fileToUri(File file) throws MalformedURLException { 58 String path = file.getAbsolutePath().replace(File.separatorChar, '/'); 59 if (path.length() > 0 && path.charAt(0) != '/') 60 path = '/' + path; 61 return new URL ("file", "", path).toString(); 62 } 63 64 public static String uriToUriOrFile(String uri) { 65 if (!uri.startsWith("file:")) 66 return uri; 67 uri = uri.substring(5); 68 int nSlashes = 0; 69 while (nSlashes < uri.length() && uri.charAt(nSlashes) == '/') 70 nSlashes++; 71 File f = new File (uri.substring(nSlashes).replace('/', File.separatorChar)); 72 if (f.isAbsolute()) 73 return f.toString(); 74 return uri.replace('/', File.separatorChar); 75 } 76 77 static public void main(String [] args) { 78 System.err.println(uriToUriOrFile(args[0])); 79 } 80 } 81 | Popular Tags |