Java FileInputStream在属性文件上失败
Java FileInputStream在属性文件上失败,java,Java,PROJECT/resources/properties.properties中的此属性文件可以通过以下方式读取并显示其内容: public void showFileContent(String fileName){ File file = new File (fileName); FileInputStream input = null; if(file.exists()){ int content; try {
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
理想情况下,我们根本不应该传递属性。我们只需要创建一个新的对象
并返回它。实际上你是对的。我只是不明白为什么我不能用新属性扩展属性,因为这是一个无休止的哈希表!?实际上,我们希望分离文件中的属性,如web.properties、db properties等。我们不需要扩展这些属性。我们可以对任何现有属性对象调用putAll
方法来添加新属性(另一个对象)。例如,Properties p=新属性();p、 putAll(p1)代码>