01: /*
02: * @(#)PathHelper.java 1.3 05/06/07
03: *
04: * Copyright (c) 1997-2004 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package org.pnuts.lib;
10:
11: import pnuts.lang.Context;
12: import java.io.File;
13:
14: /**
15: * Provides helper methods to handle files
16: */
17: public class PathHelper {
18:
19: static final String CWD = "cwd".intern();
20:
21: static boolean isRelative(File file) {
22: return !file.isAbsolute()
23: && file.getPath().charAt(0) != File.separatorChar;
24: }
25:
26: /**
27: * Gets a java.io.File object
28: *
29: * @param name the file name
30: * @param context the context in which the file name is resolved.
31: * The context-local variable 'cwd' is used as the current directory if the
32: * specified file name is not an absolute path.
33: * @return the java.io.File object that represents the file.
34: */
35: public static File getFile(String name, Context context) {
36: File file = new File(name);
37: if (isRelative(file)) {
38: String cwd = (String) context.get(CWD);
39: if (cwd == null) {
40: cwd = System.getProperty("user.dir");
41: context.set(CWD, cwd);
42: }
43: return new File(cwd, name);
44: } else {
45: return file;
46: }
47: }
48:
49: /**
50: * Sets the current directory
51: *
52: * @param dir the directory
53: * @param context the context
54: */
55: public static void setCurrentDirectory(File dir, Context context) {
56: context.set(CWD, dir.getPath());
57: }
58:
59: /**
60: * Ensure that the parent directories exist.
61: *
62: * @param file a java.io.File object
63: * @return true if all parent directories are already/successfully created.
64: */
65: public static boolean ensureBaseDirectory(File file) {
66: File dir = new File(file.getParent());
67: if (!dir.exists()) {
68: return dir.mkdirs();
69: } else {
70: return true;
71: }
72: }
73: }
|