Skip to content
Advertisement

How write path to file properties?

I wrote a program with two language. I created a file resources_in.properties. When I attempted to get properties from the file, I got the error:

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.rd.java.basic.practice.Helper.getProper(Part5.java:18) at com.rd.java.basic.practice.Helper.main(Part5.java:27)

I think it is because I have an incorrect path to properties. resources_in.properties is located at MyAppsrcmainresources_in.properties. The main class locate MyAppsrcmainjavacomrdjavabasicpracticeHelper.java

My code:

public class Helper {

    private static String getProper(String lang, String value) {
        Properties prop = new Properties();
        InputStream inputStream = Helper.class.getClassLoader().getResourceAsStream("./src/main/resources_en.properties");
        try {
            prop.load(inputStream);
        }catch (IOException e){
            System.out.println(e);
        }
        String word = prop.getProperty(value);
        return word;
    }
    public static void main(String[] args){
    System.out.println(getProper("en","car"));
    }
}

Advertisement

Answer

You are trying to load ./src/main/resources_en.properties path as a resource. This won’t work, resources are referenced not as file system files but as classpath paths. Usually it would be:

Properties prop = new Properties();
try (InputStream in =
          Helper.class.getResourceAsStream("/resources_en.properties")) {
    prop.load(in);
}

however in most build systems resources are placed under /src/main/resource while in your case the path is non-standard which can imply problems with packaging the JAR.

It also looks like you are dealing with localized resources due to locale suffix in the file name. Perhaps instead of java.util.Properties you should use java.util.ResourceBundle.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement