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

huangapple go评论72阅读模式
英文:

Java using relative path instead of absolute path

问题

我正在Java中读取文件,当我使用绝对路径时,它能正常运行。

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

然而,当我尝试使用相对路径时,会出现“没有这个文件或目录”的错误。

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

当我在终端中使用 nano ../sample_input.txt 时,它会打开该文件。

我需要添加什么内容以使相对路径起作用?

英文:

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?

答案1

得分: 1

Java可以很好地处理相对路径。因此,你的Java进程的'当前工作目录'与调用nano时的cwd不同。

你可以在Java中检查CWD。以下两种方式都可以:

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

或者:

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

你会发现它们是不同的。Java进程的cwd是由启动Java的实体设置的。如果你从命令行调用Java,它将是你在其中执行命令时所在的目录。如果你双击一个JAR文件,它将是JAR文件所在的目录。如果你在Windows上创建一个快捷方式,它将是快捷方式中列出的目录。例如:

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

在上面的示例中,cwd是/foo/bar,而不是/bar/baz

英文:

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.

huangapple
  • 本文由 发表于 2020年8月27日 22:52:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/63618663.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定