Path.get(“.”) 在我的 Java 项目中是指什么?

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

What is the Path.get(".") refering to in my Java project?

问题

在我的当前项目中,根目录为 C:\Users\Duke。调用 Path.get(".") 的 Java 类位于路径 C:\Users\Duke\src\dependencies\storage\Store.java。我需要将数据写入并保存到文件中,但由于它必须在不同的系统上运行,我无法指定绝对路径。

我调用了 Path.get(".").forEach(System.out::println),它打印出了 src 目录中的所有目录,而不是 storage 目录。这让我感到非常困惑。难道 Path.get(".") 不应该指的是代码所在的当前目录,即位于 storage 目录中的目录?

英文:

In my current project the root directory is C:\Users\Duke. The Java class which calls Path.get(".") is in the path of C:\Users\Duke\src\dependencies\storage\Store.java. I needed to write and save data to a file, but since it has to run on different systems, I could not specify the absolute path.

I did a call on Path.get(".").forEach(System.out::println) and it printed out all the directories in src instead of storage. This has left me extremely confused. Shouldn't the Path.get(".") refer to current directory of where the code resides, which is in the storage directory?

答案1

得分: 2

A . represents a 相对路径 ,指的是“工作目录”,即您的程序运行的目录。这通常 不是 源文件编译所在的目录或路径。您可以使用 Paths.get(".").toAbsolutePath() 查看它表示的确切目录。

如果您正在使用集成开发环境(IDE),很难确定它使用哪个目录作为其工作目录,但通常它将是项目根目录。您通常可以从IDE内部配置工作目录。

如果您试图加载项目中的文件,比如数据文件,您可能会发现使用资源比直接访问文件系统更好。

英文:

A . denotes a relative path to the "working directory", namely the directory your program is run from. This is typically not the directory or path of the source file(s) your program is compiled from. You can do Paths.get(".").toAbsolutePath() to see the exact directory it represents.

If you're using an IDE it can be hard to tell which directory it uses as its working directory, but typically it will be the project root. You can usually configure the working directory from within the IDE.

If you're trying to load files, such as data files, that are part of the project you may find resources better than accessing the filesystem directly.

答案2

得分: 0

"."返回应用程序的工作目录。通常情况下,这是启动Java虚拟机以执行Java类的目录。

它不能指的是代码的位置,因为代码可以存在于任何地方,例如在互联网上的某个位置,您的类加载器下载要执行的类(在旧时代[TM]中非常常见,当Java小程序仍然存在,或者使用Webstart应用时)。

英文:

. returns the application's working directory. In general that's the directory from where you are starting the Java Virtual Machine in order to execute Java classes.

It can't refer to the location of the code because that can be everywhere, e.g. some place in the internet where your classloader downloaded the classes that are executed (something that was very common in the Old Days[TM] when Java Applets were still a thing or with Webstart-applications).

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

发表评论

匿名网友

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

确定