如何在java中定义相对路径 [英] How to define a relative path in java
本文介绍了如何在java中定义相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的项目结构:
我需要阅读 MyClass.java
中的 config.properties
.我尝试使用如下相对路径这样做:
I need to read config.properties
inside MyClass.java
.
I tried to do so with a relative path as follows :
// Code called from MyClass.java
File f1 = new File("..\..\..\config.properties");
String path = f1.getPath();
prop.load(new FileInputStream(path));
这给了我以下错误:
......config.properties (The system cannot find the file specified)
如何在 Java 中定义相对路径?我正在使用 jdk 1.6 并在 Windows 上工作.
How can I define a relative path in Java? I'm using jdk 1.6 and working on windows.
推荐答案
尝试这样的事情
String filePath = new File("").getAbsolutePath();
filePath.concat("path to the property file");
所以你的新文件指向创建它的路径,通常是你的项目主文件夹.
So your new file points to the path where it is created, usually your project home folder.
正如@cmc 所说,
String basePath = new File("").getAbsolutePath();
System.out.println(basePath);
String path = new File("src/main/resources/conf.properties")
.getAbsolutePath();
System.out.println(path);
两者都给出相同的值.
这篇关于如何在java中定义相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文