简体   繁体   中英

Java's relative path in class File

here is my code:

File file1 = new File("");
System.out.println(file1.exists()); // why the output is false?
System.out.println(file1.getAbsolutePath());

// assume that my current path is "d:/xxx/yyy"
File file2 = new File(".");
System.out.println(file2.getPath());   // i want to get ""
                                       // but i actually get ".", 
                                       // which is not i want.
                                       // so how can i get ""

to sum up, what i want is an object file of class File, which when i call file.getPath() it returns "" and when i call file.exists() it returns true;

If you really just want to have the current working directory in a string, you can simply use System.getProperty("user.dir") , see System Properties .

Otherwise you'll have to use . for the "current working directory" and use File#getCanonicalPath() the get the canonical representation of this File object. Also see File#getCanonicalFile() .

To your first question: File("") is a valid path and is equivalent to System.getProperty("user.dir") . It is not a valid file or directory in that path (it still doea have a path though. This is a completely relative path, so when you call getPath() it will return an empty string since no file found by the name "".

Your second question "." is a directory, it exists, and it also has a relative path of "", so when calling getPath you will see the path "" + the directory name "."

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