Java 从另一个文件夹读取属性文件时的空指针
我的应用程序将检查属性文件是否存在,如果不存在,则创建一个属性文件Java 从另一个文件夹读取属性文件时的空指针,java,properties-file,Java,Properties File,我的应用程序将检查属性文件是否存在,如果不存在,则创建一个属性文件 try{ // create new file String path="c:\\temp\\LaserController.properties"; File file = new File(path); String comport = "Comport=COM1"; String Parity = "parity=none";
try{
// create new file
String path="c:\\temp\\LaserController.properties";
File file = new File(path);
String comport = "Comport=COM1";
String Parity = "parity=none";
String baud = "baud=9600";
String Stopbits = "StopBits=0";
String databits = "DataBits=8";
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
// write in file
bw.write(comport);
bw.newLine();
bw.write(Parity);
bw.newLine();
bw.write(baud);
bw.newLine();
bw.write(Stopbits);
bw.newLine();
bw.write(databits);
// close connection
bw.close();
}
但是当我尝试像这样读取属性文件时,我得到了一个空指针
else {
Properties prop = new Properties();
InputStream input = LaserControllerUI.class.getResourceAsStream("c:\\temp\\LaserController.properties");
// load a properties file
prop.load(input);
// get the property value and print it out
System.out.println(prop.getProperty(Comport+"comport"));
System.out.println(prop.getProperty("Parity"));
System.out.println(prop.getProperty("Baud"));
input.close();
}
}catch(Exception e){
System.out.println(e);
}
}
它在InputStream输入
行失败,但我不知道为什么。文件存在,我的应用程序可以访问它,因为它首先将文件放在那里。我做错了什么
文件必须位于用户可以访问的位置才能更改参数
getResourceAsStream
方法需要一个“类路径相对”名称。您正在提供一条绝对路径。尝试改用FileInputStream
例如:
我建议使用
Properties.save()
,以确保它是以可以读取的格式编写的
我建议你看看文本文件,看看写了什么
顺便说一句,属性区分大小写。你写
Comport
parity
baud
但是你读了
Comport+"comport"
Parity
Baud
因此,它们都将
null
将该文件移动到资源文件夹或将该文件夹添加为资源文件夹
getClass().getClassLoader().getResourceAsStream(“LaserController.properties”)
LaserControllerUI
。。。这个类是在哪里定义的,它是做什么的?“它在InputStream输入行失败”最有可能的情况是这样的,修复后,OP应该阅读我的答案+1确定,完成并固定资本化。它现在输出空值,但如果我单击comport
,它会显示写入属性文件comport=COM1
@DisplayName中的正确值。我猜您不应该查找comport+“comport”
没错,当我在eclipse中单击它时,我将其更改为comport
,它会显示属性,但不会按预期打印出“COM1”。@DisplayName它显示了什么?啊,明白了。非常感谢你的工作!对我来说,这是一条陡峭的学习曲线。
Comport+"comport"
Parity
Baud