KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > thaiopensource > util > UriOrFile


1 package com.thaiopensource.util;
2
3 import java.net.URL JavaDoc;
4 import java.net.MalformedURLException JavaDoc;
5 import java.io.File JavaDoc;
6
7 public class UriOrFile {
8   private UriOrFile() {
9   }
10
11   public static String JavaDoc toUri(String JavaDoc uriOrFile) {
12     if (!hasScheme(uriOrFile)) {
13       try {
14     return fileToUri(uriOrFile);
15       }
16       catch (MalformedURLException JavaDoc e) { }
17     }
18     return uriOrFile;
19   }
20
21   private static boolean hasScheme(String JavaDoc 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     // Don't recognize single letters as schemes
32
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 JavaDoc fileToUri(String JavaDoc file) throws MalformedURLException JavaDoc {
54     return fileToUri(new File JavaDoc(file));
55   }
56
57   public static String JavaDoc fileToUri(File JavaDoc file) throws MalformedURLException JavaDoc {
58     String JavaDoc path = file.getAbsolutePath().replace(File.separatorChar, '/');
59     if (path.length() > 0 && path.charAt(0) != '/')
60       path = '/' + path;
61     return new URL JavaDoc("file", "", path).toString();
62   }
63
64   public static String JavaDoc uriToUriOrFile(String JavaDoc 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 JavaDoc f = new File JavaDoc(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 JavaDoc[] args) {
78     System.err.println(uriToUriOrFile(args[0]));
79   }
80 }
81
Popular Tags