简体   繁体   English

Java使用相对路径而不是绝对路径

[英]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.我正在用 Java 读取文件,当我使用绝对路径时,它工作正常。

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但是,当我尝试使用相对路径时,出现 No such file or directory 错误

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

When I use my terminal and use nano ../sample_input.txt it opens up the file.当我使用我的终端并使用nano ../sample_input.txt它会打开文件。

What do I need to add to get the relative path to work?我需要添加什么才能获得工作的相对路径?

Java does relative paths just fine. Java 做相对路径就好了。 Clearly, then, the 'current working directory' for your java process is not the same as the cwd when you're invoking nano .显然,当您调用nano时,java 进程的“当前工作目录”与 cwd 不同。

You can check the CWD in java.您可以在java中检查CWD。 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. java进程的“cwd”是它被任何启动的java设置的cwd。 If you're invoking java from the command line, it'll be the directory you're in as you do so.如果您从命令行调用 java,它将是您执行此操作时所在的目录。 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.如果您双击一个 jar,它将是该 jar 所在的目录。如果您正在制作 Windows 快捷方式,它就是快捷方式中列出的目录。 Example:例子:

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

In the above example, the cwd is /foo/bar .在上面的例子中,cwd 是/foo/bar Not /bar/baz .不是/bar/baz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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