简体   繁体   中英

How does file.getAbsolutePath work?

This is the code:

String filename = "sql.txt";
File file = new File(filename);
String path = file.getAbsolutePath();
System.out.println(path);

My text file resides in E drive but when I print out the path it is in C drive. Why does this happen?

You have provided a path which is neither absolute nor canonical.

String filename = "sql.txt";

Hence, the pathname is returned as simply the current user directory.

Have a look at the documentation for the getAbsolutePath() method in the File class:

If this abstract pathname is already absolute, then the pathname string is simply returned as if by the getPath() method. If this abstract pathname is the empty abstract pathname then the pathname string of the current user directory, which is named by the system property user.dir, is returned. Otherwise this pathname is resolved in a system-dependent way. On UNIX systems, a relative pathname is made absolute by resolving it against the current user directory. On Microsoft Windows systems, a relative pathname is made absolute by resolving it against the current directory of the drive named by the pathname, if any; if not, it is resolved against the current user directory.

Follow those steps

  • Go to run configuration
  • Click argument tab
  • Change the working directory to ${workspace_loc:myproject}

Reference Java workspace and file path

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