简体   繁体   中英

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 MyApp\src\main\resources_in.properties . The main class locate MyApp\src\main\java\com\rd\java\basic\practice\Helper.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"));
    }
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM