java Java中的相对路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11259773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
relative path in Java
提问by comatose
My program has to use certain files that reside in another directory. Right now I am using absolute path to specify the location of the files. But I know that the relative position of these files will remain the same compared to where my program is residing. How I can use relative path in Java to specify the location of these files?
我的程序必须使用驻留在另一个目录中的某些文件。现在我使用绝对路径来指定文件的位置。但是我知道与我的程序所在的位置相比,这些文件的相对位置将保持不变。如何在 Java 中使用相对路径来指定这些文件的位置?
For example my program is residing in
例如我的程序驻留在
/home/username/project/src/com/xyz/
..and the target files are in..
..并且目标文件在..
/home/username/project/secure/
回答by Stephen C
For example my program is residing in /home/username/project/src/com/xyz/
and the target files are in /home/username/project/secure/
例如我的程序驻留在 /home/username/project/src/com/xyz/
并且目标文件在 /home/username/project/secure/
Knowing the place where your program's source code resides does not help. What you need to know is the current directory of the program when it is executed. That could be literally anything. Even if you are launching the application from (for example) Eclipse, the application launcher allows you to specify the "current directory" for the child process in the Run configuration.
知道程序源代码所在的位置无济于事。您需要知道的是程序在执行时的当前目录。那可以是任何字面上的东西。即使您是从(例如)Eclipse 启动应用程序,应用程序启动器也允许您在运行配置中为子进程指定“当前目录”。
回答by Akhi
Your current path.
您当前的路径。
currentPath= /home/username/project/src/com/xyz/;
Relative path to "/home/username/project/secure/" folder is
“/home/username/project/secure/”文件夹的相对路径是
relativePath= ../../../secure;
回答by Mohammad Adil
In Java you can use getParentFile()
to traverse up the tree.
在 Java 中,您可以使用getParentFile()
遍历树。
File currentDir = new File(".");
File parentDir = currentDir.getParentFile();
This will be safe as you are not using system dependent file separator (../)
这将是安全的,因为您没有使用系统相关文件分隔符 (../)