FileInputStream在属性文件上失败

时间:2016-03-07 13:57:37

标签: java

可以阅读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)

任何人都知道为什么对于两种方法都可以在同一路径上使用属性文本文件?

1 个答案:

答案 0 :(得分:3)

由于第一个代码段有效,似乎properties作为null传递给getProperties()方法,从而产生NullPointerException

理想情况下,我们根本不应该通过properties。我们只需要创建一个新的object并将其返回。