/Users/lyon/j4p/src/classUtils/pack/util/PathNormalizer.java
|
1 package classUtils.pack.util;
2
3 import java.io.File;
4 import java.util.ArrayList;
5 import java.util.Iterator;
6 import java.util.List;
7 import java.util.StringTokenizer;
8
9
10 /**
11 * An utility class to compute normalized paths (i.e. paths that do not contain
12 * neither "." nor "..")
13 *
14 * @author C. Sadun
15 * @version 1.0
16 */
17 public class PathNormalizer {
18
19 /**
20 * Normalizes a file object. The returned file object will
21 * return the normalize path when File.getAbsolutePath() is invoked.
22 * @param path the File object to be normalized
23 * @return a File object whose absolute path name is normalized
24 */
25 public static File normalize(File path) {
26 return new File(normalizePath(path.getAbsolutePath()));
27 }
28
29 /**
30 * Normalizes a string path. The returned path does not
31 * contain ".." or "." references
32 * @param path the path to be normalized.
33 * @return a String object containing the normalized path
34 */
35 public static String normalizePath(String path) {
36 File f = new File(path);
37 boolean trailingFSep=path.endsWith(File.separator);
38 path=f.getAbsolutePath();
39 StringTokenizer st = new StringTokenizer(path, File.separator);
40 List names=new ArrayList();
41 while(st.hasMoreTokens()) {
42 String step = st.nextToken();
43 if (".".equals(step)) continue;
44 else if ("..".equals(step)) names.remove(names.size()-1);
45 else names.add(step);
46 }
47
48 StringBuffer sb = new StringBuffer();
49 for(Iterator i=names.iterator(); i.hasNext(); ) {
50 sb.append(i.next());
51 if (i.hasNext()) sb.append(File.separator);
52 }
53 if (trailingFSep)
54 sb.append(File.separator);
55 return sb.toString();
56 }
57
58 }