01: package org.jicengine.io;
02:
03: import java.io.File;
04: import java.util.StringTokenizer;
05:
06: /**
07: *
08: * <p>
09: * Copyright (C) 2004 Timo Laitinen
10: * </p>
11: * @author Timo Laitinen
12: * @created 2004-09-20
13: * @since JICE-0.10
14: */
15: public class PathResolver {
16:
17: private static final String DIRECTORY_SEPARATOR = "/";
18:
19: /**
20: * <p>
21: * Forms a real path from a base-path and a relative path.
22: * </p>
23: *
24: * <p>
25: * For example, <br>
26: * <code>'/directory/file1.txt' + 'file2.txt' -> '/directory/file2.txt'</code><br>
27: * <code>'/directory/file1.txt' + '../file2.txt' -> '/file2.txt'</code><br>
28: * <code>'/directory/subdir/' + 'file2.txt' -> '/directory/subdir/file2.txt'</code><br>
29: * <code>'/directory/file1.txt' + 'subdir/' -> '/directory/subdir/'</code><br>
30: * </p>
31: *
32: * @param contextPath
33: * @param relativePath
34: */
35: public static String getRealPath(String contextPath,
36: String relativePath) {
37: File baseFile;
38: if (contextPath.endsWith(DIRECTORY_SEPARATOR)
39: || contextPath.endsWith(File.separator)) {
40: // a directory
41: baseFile = new File(contextPath);
42: } else {
43: // not a directory, so use the parent-file as the base-file.
44: // the parent-file should be a directory..
45: baseFile = new File(contextPath).getParentFile();
46: }
47:
48: File newFile = new File(baseFile, relativePath);
49:
50: String realPath = getPathOf(newFile);
51:
52: // directories must end in '/'.
53: // unfortunately the java.io.File discard the trailing '/'.
54: // we'll add it manually.
55: if (relativePath.endsWith(DIRECTORY_SEPARATOR)
56: && !realPath.endsWith(DIRECTORY_SEPARATOR)) {
57: realPath = realPath + DIRECTORY_SEPARATOR;
58: }
59:
60: return realPath;
61: }
62:
63: public static String getPathOf(File file) {
64: String path;
65: if (File.separator.equals(DIRECTORY_SEPARATOR)) {
66: // no need to do any conversions
67: path = file.getPath();
68: } else {
69: // convert the windows file-separator to the unix-style that we are using.
70: StringTokenizer tokenizer = new StringTokenizer(file
71: .getPath(), File.separator, true);
72: String token;
73: StringBuffer pathBuffer = new StringBuffer();
74: while (tokenizer.hasMoreElements()) {
75: token = tokenizer.nextToken();
76: if (token.equals(File.separator)) {
77: pathBuffer.append(DIRECTORY_SEPARATOR);
78: } else {
79: pathBuffer.append(token);
80: }
81: }
82: path = pathBuffer.toString();
83: }
84:
85: return path;
86: }
87:
88: }
|