java - 使用输入流读取 java 属性文件

标签 java

我在使用 InputStream 和类 Loader 函数时遇到空指针异常,但在使用 FileInputStream 时它正在正确读取属性文件。

为什么我会收到这个错误?下面给出的是我的代码。

public String readProperties()
{

    String result = "";
    Properties prop = new Properties();
    String file = "test.properties";
    //InputStream fins = getClass().getClassLoader().getResourceAsStream(file); 
    try 
    {
        prop.load(new FileInputStream(file));
        //prop.load(fins);
    } 
    catch (IOException e) {
        e.printStackTrace();
    }

    String nation = prop.getProperty("Nation");
    String city = prop.getProperty("City");
    String state = prop.getProperty("State");
    result = "I live in "+city+" in "+state+" in "+nation;
    return result;
}

最佳答案

确保将 test.properties 文件保存在类路径中:即在应用程序的 Src 文件夹中

这里是示例代码:

package com.example;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ReadProperties {

    public static void main(String[] args) {        

        ReadProperties r = new ReadProperties();        
        String  result = r.readProperties();
        System.out.println("Result   : " + result);
    }

    public String readProperties()
    {
        String result = "";
        Properties prop = new Properties();
        String file = "test.properties";
        InputStream fins = getClass().getClassLoader().getResourceAsStream(file); 
        try 
        {
            //prop.load(new FileInputStream(file));
            if(fins!=null)
                prop.load(fins);        
        } 
        catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }

        String nation = prop.getProperty("Nation");
        String city = prop.getProperty("City");
        String state = prop.getProperty("State");
        result = "I live in "+city+" in "+state+" in "+nation;
        return result;
    }

}

关于java - 使用输入流读取 java 属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26967352/

相关文章:

java - Angular 客户端向 Java 服务器发送 POST 请求的参数

java - 使用 Spring MVC 的 XML View

java - 用于读取和写入文件的正确 Java 类?

java - JSP 的 Tomcat 类重新加载

java - getImage()/drawImage() 使 Java-Applet 停止工作

java - 检查网站是否存在

java - spring boot、logback 和 logging.config 属性

java - 无法获取正在运行的 jar 的名称

java - Java 中的 Spring 配置 - 创建和使用 2 个相同类的 bean 不使用 Autowired

java - 从jdk6调用jdk 7编译的类