Loading a property file by reading line by line from another file

淺唱寂寞╮ 提交于 2020-02-01 05:46:05

问题


I am reading a file called abc.txt and each line of abc.txt is an properties file. For eg:-

label.properties
label_ch.properties
label_da.properties
label_de.properties
label_en.properties

So after reading each line I am getting properties file in String line, and after that I am trying to load that properties file but it is not getting loaded. Any thing wrong with my implementation?

This is my code-

package testing.project;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Properties;

public class Project {

    public static void main(String[] args) {
    BufferedReader br = null;
    HashMap<String, String> hashMap = new LinkedHashMap<String, String>();
    try {
        br = new BufferedReader(new FileReader("C:\\apps\\apache\\tomcat7\\webapps\\examples\\WEB-INF\\classes\\abc.txt"));
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();
        loadProperties(line);

        while (br.readLine() != null) {
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
        String everything = sb.toString();
        System.out.println(everything);
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    }
     catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    }

    private static void loadProperties(String line) {
        Properties prop = new Properties();
        InputStream in = Project.class.getResourceAsStream(line);
        try {
//As soon as it gets into prop.load(in), cursor goes to br.close that is in main method.
                prop.load(in);
                for(Object str: prop.keySet()) {
                    Object value = prop.getProperty((String) str);
                    System.out.println(str+" - "+value);
                }
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }


        }

    }

I am getting error as-

Exception in thread "main" java.lang.NullPointerException
    at java.util.Properties$LineReader.readLine(Unknown Source)
    at java.util.Properties.load0(Unknown Source)

回答1:


Going through your code it appears all is good except for the ones mentioned above as well. Instead of writing

    String line = br.readLine();
    loadProperties(line);

    while (br.readLine() != null) {
        sb.append(line);
        sb.append("\n");
        line = br.readLine();
    }

prefer to write

String line = null;
while ((line = br.readLine()) != null) 
{
    loadProperties(line);
    sb.append(line);
    sb.append("\n");
    line = br.readLine();
}

Moreover, since it's a java code, so prefer to put forward slash (/) instead of two backslashes(\), while describing a path to a file.

For Example :

BufferedReader br = new BufferedReader(new FileReader("C:/Apache/tomcat/webapps/GaganIsOnline/WEB-INF/classes/names.txt"));

And please do check, if the file path is proper, mean to say, does the said file abc.txt do exists in that given location.

Regards.




回答2:


EDIT: If you're getting a NullPointerException within prop.load(in), it's possible that

Project.class.getResourceAsStream(line)

is returning null. You should check for that (and also close the input stream in a finally block). Are you sure label.properties is actually present and available to the class loader? How are you running this code? If you're using Eclipse or something similar, you may have forgotten to tell it that your label.properties file is a resource which should be copied to the output directory.


Well here's one problem:

while (br.readLine() != null) {
    sb.append(line);
    sb.append("\n");
    line = br.readLine();
}

That's going to skip every other line. Typically I'd use:

while ((line = br.readLine()) != null) {
    sb.append(line);
    sb.append("\n");
}

Note that only the first line of your file is being used to load a properties file - the rest is just dumped to System.out. Also, the properties file you are loading is then being thrown away - you don't do anything with prop afterwards. (And you should close in in a finally block, assuming it's non-null.)




回答3:


Once you fixed the bug mentioned above. Here is the solution to the problem:

enum PathType {RESOURCE, ABSOLUTE}

private static void loadProperties(String line, PathType pathType) {
    Properties prop = new Properties();
    InputStream in = null;
    if (pathType == PathType.RESOURCE)
        in = PropertyTest.class.getResourceAsStream(line);
    else {
        try {
            in = new FileInputStream(line);
        } catch (FileNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    try {
//As soon as it gets into prop.load(in), cursor goes to br.close that is in main method.
        prop.load(in);
        for (Object str : prop.keySet()) {
            Object value = prop.getProperty((String) str);
            System.out.println(str + " - " + value);
        }
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Code to call it. There are various ways.

  • If you want to load properties from base of the class loader. For example, if I am running my application with main function from eclipse, my base will be <some_path>/classes. So the file label.properties is residing there. Also if you are running from Tomcat and label.properties lies in <your_web_app>/classes. Use the code below:

    loadProperties("/" + line, PathType.RESOURCE); // Load from base path of class loader

  • If you want to load properties from package folder of the class loader. For example, if I am running my application with main function from eclipse, my base will be <some_path>/classes. The file label.properties is residing in <some_path>/classes/testing/project. Also if you are running from Tomcat and label.properties lies in <your_web_app>/classes/testing/project use below code:

    loadProperties(line, PathType.RESOURCE); // Load from base path of class loader + the package path

  • If you want load properties from any absolute path on your hard drive. Use below code:

    loadProperties("C:\\apps\\apache\\tomcat7\\webapps\\examples\\WEB-INF\\classes\\" + line, PathType.ABSOLUTE);

NOTE: Please handle the exception as per your needs. I just updated your code AS IS.




回答4:


Method br.readLine() is called twice in your code.

 while (line != null) {
   loadProperties(line);
   sb.append(line);
   sb.append("\n");
   line = br.readLine();
 }


来源:https://stackoverflow.com/questions/8207855/loading-a-property-file-by-reading-line-by-line-from-another-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!