英文:
Confusion over current working directory in File’s getAbsolutePath method
问题
文件的getAbsolutePath
方法有一个倾向,如果在文件构造函数中提供相对路径或仅提供文件名,它将通过在当前工作目录前缀绝对路径来解析路径。
当前工作目录的定义是我们运行Java程序的目录。
在我的示例中,我的Java程序位于D:\my-app\src\App.java
内。
当我执行System.out.println(System.getProperty("user.dir"));
时,
它应该理想地打印D:\my-app\src
,
但实际上它打印的是D:\my-app
。
为什么会这样呢?
英文:
The file’s getAbsolutePath has the tendency that if a relative path or just the file name is provided in the file constructor, then it will resolve the absolute path by prefixing the current working directory.
The definition of current working directory is the directory where we run our Java Program.
In my example, my java program resides inside D:\my-app\src\App.java
When I do a System.out.println(System.getProperty("user.dir"));
Then it should ideally print D:\my-app\src
But it is actually printing D:\my-app
Why is it so?
答案1
得分: 1
当您从IntelliJ启动应用程序时,其工作目录会根据在“运行/调试配置”对话框中设置的内容进行设置。
在那里,您可以将工作目录设置为固定值,例如D:\my-app\src
。另一个选项是使用路径变量。可用的变量列表显然取决于许多因素 - 打开对话框并查看可用内容。我看到的一个选项是$FileDir$
,我想这可能是源代码文件的目录。
英文:
When you start an application from IntelliJ, its working directory is set according to what's set in "Working directory" in the "Run/Debug Configurations" dialog.
There, you can set the working directory to a fixed value such as D:\my-app\src
. Another option is to use a path variable. The list of variables that are available apparently can depend on many things - open the dialog and see what's available. One option that I see is $FileDir$
which I imagine would be the directory of the source code file.
答案2
得分: 0
我认为我找到了解决方案。实际上,是Intellij在隐式地将src文件夹设置为源文件夹,导致了这个问题。我是通过进入Intellij内的模块设置找到的这个问题的。
当我从命令提示符中运行相同的操作时,会选择正确的工作目录,即 D:\my-app\src\
。
英文:
I think I found the solution. Intellij was actually causing the issue by implicitly setting the src folder as the source folder. I found it by going to the module setting within Intellij.
When I ran the same from a command prompt, the correct working directory i.e. D:\my-app\src\
is selected.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论