简体   繁体   中英

Java using relative path instead of absolute path

I am reading in a file in Java and when I use the absolute path it works fine.

File myObj = new File("/Users/aaronmk2/Downloads/demo2/SystemDependencies/src/sample_input.txt");

However, when I try to use the relative path I get a No such file or directory error

File myObj = new File("../sample_input.txt");

When I use my terminal and use nano ../sample_input.txt it opens up the file.

What do I need to add to get the relative path to work?

Java does relative paths just fine. Clearly, then, the 'current working directory' for your java process is not the same as the cwd when you're invoking nano .

You can check the CWD in java. Either way will work:

System.out.println(new File(".").getAbsolutePath());

or:

System.out.println(System.getProperty("user.dir"));

You should find that it is different. The 'cwd' for a java process is the cwd that it was set to by whatever started java. If you're invoking java from the command line, it'll be the directory you're in as you do so. If you are double clicking a jar, it'll be the directory the jar is in. If you're making a windows shortcut, it's the directory listed in the shortcut. Example:

cd /foo/bar
java -jar /bar/baz/hello.jar

In the above example, the cwd is /foo/bar . Not /bar/baz .

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