gpt4 book ai didi

java - FileInputStream 在属性文件上失败

转载 作者:行者123 更新时间:2023-11-29 04:49:54 25 4
gpt4 key购买 nike

PROJECT/resources/properties.properties 中的属性文件可以读取并显示其内容:

public void showFileContent(String fileName){

File file = new File (fileName);
FileInputStream input = null;

if(file.exists()){
int content;
try {
input = new FileInputStream(fileName);
while ((content = input.read()) != -1) {
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (input != null) {
try {
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}else{
System.out.println("Error : properties File " + fileName + " not found");
}
}

但是它失败了,在 properties.load 中出现空指针异常

public Properties getProperties(String fileName, Properties properties){

File file = new File (fileName);
InputStream input = null;

if(file.exists()){
try {
input = new FileInputStream(fileName);
properties.load(input);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}else{
System.out.println("Error : properties File " + fileName + " not found");
}
return properties;
}

即使输入设置为

input = this.getClass().getClassLoader().getResourceAsStream(fileName)

任何人都知道为什么这可以用于两种方法的同一路径下的属性文本文件?

最佳答案

由于第一个代码片段有效,似乎 properties 被作为 null 传递给 getProperties() 方法,导致 NullPointerException

理想情况下,我们根本不应该传递属性。我们只需要创建一个新的 object 并返回它。

关于java - FileInputStream 在属性文件上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35845636/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com