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

huangapple go评论40阅读模式

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


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

我调用了 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\ 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?


得分: 2

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




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.


得分: 0




. 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).

  • 本文由 发表于 2020年8月23日 03:20:22
  • 转载请务必保留本文链接:



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