简体   繁体   中英

Java parse File-path with different working directory

I have a file which contain several paths, like . (relative) or /Users/...../ (absolut). I need to parse the paths that are relative to the directory of the file that contains the paths and not the working-directory and create correct File-instances. I can not change the working directory of the Java-Program, since this would alter the behaviour of other components and i also have to parse several files. I don't think public File(String parent, String child) does what i want, but i may be wrong. The documentation is quite confusing.

Example:

file xy located under /system/exampleProgram/config.config has the following content:
.
/Users/Name/file
./extensions

i want to resolve these to:
/system/exampleProgram/
/Users/Name/file
/system/exampleProgram/file/

So, I am going to assume that you have access to the path of the file you opened (either via File.getAbsolutePath() if it was a File descriptor or via a regex or something)...

Then to translate your relative paths into absolute paths, you can create new File descriptions with your opened file, like so:

File f = new File(myOpenedFilePath);
File g = new File(f, "./extensions");
String absolutePath = g.getCanonicalPath();

When you create a file with a File object and a String , Java treats the String as a path relative to the File given as a first argument. getCanonicalPath will get rid of all the redundant . and .. and such.

Edit: as Leander explained in the comments, the best way to determine whether the path is relative or not (and thus whether it should be transformed or not) is to use file.isAbsolute() .

Sounds like you probably want something like


    File fileContainingPaths = new File(pathToFileContainingPaths);
    String directoryOfFileContainingPaths =
    fileContainingPaths.getCanonicalFile().getParent();
    BufferedReader r = new BufferedReader(new FileReader(fileContainingPaths));
    String path;
    while ((path = r.readLine()) != null) {
       if (path.startsWith(File.separator)) {
          System.out.println(path);
       } else {
          System.out.println(directoryOfFileContainingPaths + File.separator + path);
       }
    }       
    r.close();

Don't forget the getCanonicalFile() . (You might also consider using getAbsoluteFile() ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM