如何在eclipse中从另一个java项目读取项目的属性文件
我想从项目Test1(src/Test1.java)中读取项目测试的bean.properties文件(在src/conf/bean.properties中)。我已经通过java构建路径和使用如何在eclipse中从另一个java项目读取项目的属性文件,java,eclipse,properties-file,Java,Eclipse,Properties File,我想从项目Test1(src/Test1.java)中读取项目测试的bean.properties文件(在src/conf/bean.properties中)。我已经通过java构建路径和使用 Properties prop = new Properties(); prop.load(new FileInputStream("src/conf/bean.properties")); 我越来越 java.io.FileNotFoundException: src\conf\bean.proper
Properties prop = new Properties();
prop.load(new FileInputStream("src/conf/bean.properties"));
我越来越
java.io.FileNotFoundException: src\conf\bean.properties (The system cannot find the path specified)
at java.io.FileInputStream.open0(Native Method)
以下是读取属性文件的示例代码:-
public class ReadPropertiesFile {
public static void main(String[] args) {
try {
File file = new File("test.properties");
FileInputStream fileInput = new FileInputStream(file);
Properties properties = new Properties();
properties.load(fileInput);
fileInput.close();
Enumeration enuKeys = properties.keys();
while (enuKeys.hasMoreElements()) {
String key = (String) enuKeys.nextElement();
String value = properties.getProperty(key);
System.out.println(key + ": " + value);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
或者您可以使用:-
Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("foo.properties");
prop.load(in);
in.close();
这样的事情是不可能的!!!必须指定绝对路径才能访问类路径之外的文件。
无论何时编写“src/conf/bean.properties”,它都会指定该文件的相对路径。此类文件将仅在类路径中搜索。请考虑将属性文件放在类路径中。在Eclipse中,它可能是这样的
Project1
+- src
+- bean.properties
Project2
+- src
+- ReadPropertiesTest.java
然后转到Project2的属性,然后是“Java构建路径”,然后是“Projects”,并将Project1添加到列表中
现在,您可以使用类加载器读取文件,如下所示:
InputStream stream = ReadPropertiesTest.class.getClassLoader()//
.getResourceAsStream("/bean.properties");
Properties properties = new Properties();
properties.load(stream);
// ... closing code here
请注意属性文件名称前的斜杠/