猿问

与getClassLoader()方法有关的问题:为什么下面的代码中会发生空指针异常

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

public class PropertyUtil {
    public static void main(String[] args) {
        Properties properties = new Properties();
        try {
            properties.load(PropertyUtil.class.getClassLoader().getResourceAsStream("LYZ.properties"));
            String username = properties.getProperty("username");

            System.out.println(username);
        } catch (IOException e) {
            System.out.println("无法读取LYZ.properties");
        }
    }
}

控制台信息

Exception in thread "main" java.lang.NullPointerException
    at java.util.Properties$LineReader.readLine(Properties.java:434)
    at java.util.Properties.load0(Properties.java:353)
    at java.util.Properties.load(Properties.java:341)
    at com.test.PropertyUtil.main(PropertyUtil.java:10)

第十行代码就是:
properties.load(PropertyUtil.class.getClassLoader().getResourceAsStream("LYZ.properties"));
 
繁华开满天机
浏览 501回答 1
1回答
随时随地看视频慕课网APP

相关分类

Java
我要回答