ish*_*shk 36 java relative-path jdk1.6
这是我的项目的结构:

我需要阅读config.properties内部MyClass.java.我尝试使用相对路径进行如下操作:
// Code called from MyClass.java
File f1 = new File("..\\..\\..\\config.properties");
String path = f1.getPath();
prop.load(new FileInputStream(path));
Run Code Online (Sandbox Code Playgroud)
这给了我以下错误:
..\..\..\config.properties (The system cannot find the file specified)
Run Code Online (Sandbox Code Playgroud)
如何在java中定义相对路径?我正在使用jdk 1.6并在Windows上工作.
Vin*_*uri 69
尝试这样的事情
String filePath = new File("").getAbsolutePath();
filePath.concat("path to the property file");
Run Code Online (Sandbox Code Playgroud)
因此,您的新文件指向创建它的路径,通常是项目主文件夹.
[编辑]
正如@cmc所说,
String basePath = new File("").getAbsolutePath();
System.out.println(basePath);
String path = new File("src/main/resources/conf.properties")
.getAbsolutePath();
System.out.println(path);
Run Code Online (Sandbox Code Playgroud)
两者都给出了相同的价值.
首先,在这里查看绝对路径和相对路径之间的区别:
绝对路径始终包含根元素和定位文件所需的完整目录列表。
或者,需要将相对路径与另一个路径组合以访问文件。
在构造函数 File(String pathname) 中,Javadoc 的 File 类说
路径名,无论是抽象的还是字符串形式的,都可以是绝对的或相对的。
如果要获取相对路径,必须定义从当前工作目录到文件或目录的路径。尝试使用系统属性来获取。如你绘制的图片:
String localDir = System.getProperty("user.dir");
File file = new File(localDir + "\\config.properties");
Run Code Online (Sandbox Code Playgroud)
而且,你应该尽量避免使用类似的“.”、“../”、“/”等类似的相对于文件位置的相对路径,因为当文件被移动时,更难处理。
| 归档时间: |
|
| 查看次数: |
200546 次 |
| 最近记录: |