Why by calling new File(".").getAbsolutePath() I get completely different path from my project's location?

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

Why by calling new File(".").getAbsolutePath() I get completely different path from my project's location?

问题

我的项目位于这里:

D:/WorkSpace/PuzzleApp

但当我调用

new File(".").getAbsolutePath();

我得到:

D:\!Documents\Desktop\.

为什么?如何修复这个问题?

我正在使用Eclipse。

英文:

My project is located here:

D:/WorkSpace/PuzzleApp

but when I am calling

new File(".").getAbsolutePath();

I get:

D:\!Documents\Desktop\.

Why? And how to fix this?

I'm using Eclipse.

答案1

得分: 2

当你打开相对路径为"."的文件时,该路径是相对于当前进程的工作目录。

通常情况下,进程的工作目录是从父进程继承的(例如,如果你在终端上运行应用程序,则当前终端的工作目录将成为你的进程的工作目录)。

在应用程序中使用相对路径被认为是一个不好的主意,因为你无法控制该进程的工作目录。但是,使用绝对硬编码路径也会带来一些问题,不能称为良好的实践。

有几种解决此问题的方法:

  1. 使用相对于非硬编码绝对路径的路径。该绝对路径应外部化为环境变量、属性文件等。
// 从外部系统变量获取目录路径
String myAbsolutePath = System.getenv("LOCAL_STORAGE_DIR");
  1. 使用相对于应用程序根目录的路径。这允许您读取甚至位于.jar或.war归档内的文件。
// 此路径看起来是绝对的,但路径的根目录是你项目的根目录
InputStream stream = MyClass.class.getResourceAsStream("/dir/another/file.txt");

但你应该明白,你的应用程序不会在IDE项目文件夹内运行。它将部署在生产服务器/用户桌面/Android设备环境中,通常会打包成jar/war/ear/...归档文件。这意味着你将无法访问你的src文件夹或类似的内容。

英文:

When you open File with relative path "." this path is relative to the current process' working directory.
Usually, the process working directory is inherited from the parent process (e.g. if you run your app with Terminal - the current terminal's working directory will be your process' working dir).

Using a relative path inside your application is considered a bad idea because you can not control this process' working directory.
But using an absolute hardcoded path also goes with some problems and can't be called a good practice.

There are several ways to solve the issue:

  1. Use a path relative to some NOT hardcoded absolute path. This absolute path should be externalized to environment variables, properties files, etc.
//Getting the directory path from the external system variable
String myAbsoultePath = System.getenv("LOCAL_STORAGE_DIR");
  1. Use a path relative to your application root. It allows you to READ files even located inside .jar or .war archives.
//This path looks absolute, but the path's root is your project's root
InputStream stream = MyClass.class.getResourceAsStream("/dir/another/file.txt");

But you should understand, that your application won't run inside your IDE project folder. It will be deployed in a production server/user's desktop/android device environment and usually, it is packed in a jar/war/ear/... archive. It means that you won't have access to your src folder or something like this.

huangapple
  • 本文由 发表于 2023年6月1日 23:24:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76383470.html
匿名

发表评论

匿名网友

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

确定