Questions related to the getClassLoader () method: why a null pointer exception occurs in the following code

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"));
 
Mar.07,2021

this is where the pointer should be reported

PropertyUtil.class.getClassLoader().getResourceAsStream("LYZ.properties")

then the most likely reason is that the resource file was not found. You need to confirm the path where the file is located, because you are giving a relative path, that is, LYZ.properties should be the same as the directory where PropertyUtil resides.

Menu