java - FileInputStream 在属性文件上失败

标签 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)

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

最佳答案

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

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

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

相关文章:

java - 用渐变填充颜色数组

java - 使用 JNI 从 Cocoa 调用 Java 类函数

java - maven - 强制将 JDBC4 包含在 JAR 中

java - 如何实现具有恒定追加和随机访问时间的不可变集合?

java - 多次循环一个方法会导致错误

java - 有没有办法在 Eclipse 中查看类方法的列表及其长度(行数)?

java - 有人有过使用 JODB 进行网络应用程序的经验吗?

java - 在不使用数据源的情况下以 SmartGWT 的动态形式上传文件时从 GWT 中的 Servlet 获取回调

java - Applet 和 Servlet 通信 block GUI

java - 如何将 java cmd 参数与正则表达式匹配?