为什么相对路径会不断变化,如何防止这种情况发生?

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

Why does relative path keep changing and how to prevent it?

问题

我使用Java创建一个名为"myCoolFolder"的文件夹,方法如下:

Files.createDirectories(Path.of("MyCoolFolder"));

这是一个相对路径。令我惊讶的是,这个文件夹有时会在文件夹结构中创建得更深或更浅一级,我不知道这种可疑行为的原因。也许它取决于我如何运行项目以及它认为的 '工作目录',但我并不确定。如何确保它始终是相同的文件夹?

英文:

I use Java to create a folder "myCoolFolder" like this:


Files.createDirectories(Path.of("MyCoolFolder"));

This is relative path. What surprises me is this - the folder sometimes is created one level deeper or higher in the folder structure and I do not know the reason for that suspicious behavior. Maybe it depends on the way I run the project and what it thinks is the 'working directory', but I'm not really sure about that. How can I make sure it is always the same folder?

答案1

得分: 2

相对路径名是相对于解析它的进程的工作目录来解析的。

如果它在不同的时间解析为不同的位置,那么要么该进程(应用程序)是在不同的工作目录中启动的,要么(可能)它正在改变其工作目录。(Java进程没有一种可移植的方式来更改自己的工作目录。)

我该如何确保它始终是相同的文件夹?

要么确保使用相同(正确)的工作目录启动Java应用程序,要么为文件夹使用绝对路径名。

英文:

A relative pathname is resolved relative to the working directory of the process that resolves it.

If it is resolving to different locations at different times then either the process (application) is started with (in) a different working directory, or (possibly) it is changing its working directory. (There isn't a portable way for a Java process to change its own working directory.)

> How can I make sure it is always the same folder?

Either make sure that you launch your Java application with the same (correct) working directory, or use an absolute pathname for the folder.

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

发表评论

匿名网友

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

确定