[英]Unable to read properties file from java
我无法从文件中读取属性。 当我尝试打印时,它为我提供了null;当我调试时,我了解到它没有在pro.Load()
函数中加载文件。 但是我的路径是正确的,但仍然无法加载文件
package AdvancedJava;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
public class ReadingPropertiesFile {
public static void main(String[] args) throws FileNotFoundException {
Properties pro = new Properties();
String path = "C://Users//310259741//Documents//ProjectManagment//JavaBasics//object.properties";
// BufferedReader reader = new BufferedReader(new FileReader(path));
File f = new File(path);
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
pro.load(fis);
}
catch (IOException e) {
System.out.println(e.getMessage());
}
System.out.println(pro.getProperty("lastname"));
}
}
属性文件内容
firstname = John
lastname = harry
Automation = Selenium
我认为问题出在道路上:
String path = "C://Users//310259741//Documents//ProjectManagment//JavaBasics//object.properties";
应该是这样的:
String path = "C:\\Users\\310259741\\Documents\\ProjectManagment\\JavaBasics\\object.properties";
另外,请确保您具有属性文件的正确路径。 如果它在您的项目中,则路径应如下所示:
String path = "C:\\...\\ProjectFolder\\src\\main\\resources\\object.properties";
您的示例对我来说很好。 但是,如果没有堆栈跟踪,我们将无法帮助您解决所获得的NPE。
无论如何,我有一些关于您的代码的提示。 我建议在使用FileInputStream
对资源使用FileInputStream
资源,以确保一旦完成将关闭资源。
您可以避免使用new File(path);
。 相反,我建议使用java.nio.*
包中的Paths
。 基于您的代码片段的示例如下:
public static void main(String[] args) {
Properties properties = new Properties();
try (FileInputStream stream = new FileInputStream(Paths.get("E:\\test\\file.txt").toFile())) {
properties.load(stream);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(properties.getProperty("lastname"));
}
使用Paths
的优点是(如果您没有记错的话)它们与系统无关,这意味着您无需担心提供正确的路径定界符。
实际上,路径应该使用另一个分隔符
"C:\\Users\\310259741\\Documents\\ProjectManagment\\JavaBasics\\object.properties";
但我建议您-将您的应用属性文件存储在资源文件夹下,有点:
src/main/resources/config.properties
这样您就可以像下面这样访问该文件:
public Properties extractFrom(String fileName) {
Properties properties = new Properties();
try (InputStream inputStream = PropertiesExtractor.class
.getClassLoader().getResourceAsStream(fileName)) {
properties.load(inputStream);
} catch (IOException ex) {
throw new RuntimeException("Cannot load properties", ex);
}
return properties;
}
extractFrom("config.properties");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.