developer tip

Java에서 속성 파일 읽기

optionbox 2020. 8. 19. 07:57
반응형

Java에서 속성 파일 읽기


속성 파일을 읽으려는 다음 코드가 있습니다.

Properties prop = new Properties();
ClassLoader loader = Thread.currentThread().getContextClassLoader();           
InputStream stream = loader.getResourceAsStream("myProp.properties");
prop.load(stream);

마지막 줄에서 예외가 발생합니다. 구체적으로 특별히:

Exception in thread "main" java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:418)
at java.util.Properties.load0(Properties.java:337)
at java.util.Properties.load(Properties.java:325)
at Assignment1.BaseStation.readPropertyFile(BaseStation.java:46)
at Assignment1.BaseStation.main(BaseStation.java:87)

고마워, 니 코스


예외에 InputStream따라이 null이며 이는 클래스 로더가 속성 파일을 찾지 못한다는 것을 의미합니다. myProp.properties가 프로젝트의 루트에 있다고 생각합니다.이 경우 선행 슬래시가 필요합니다.

InputStream stream = loader.getResourceAsStream("/myProp.properties");


이 페이지에서 정보를 찾을 수 있습니다 :
http://www.mkyong.com/java/java-properties-file-examples/

Properties prop = new Properties();
try {
    //load a properties file from class path, inside static method
    prop.load(App.class.getClassLoader().getResourceAsStream("config.properties"));

    //get the property value and print it out
    System.out.println(prop.getProperty("database"));
    System.out.println(prop.getProperty("dbuser"));
    System.out.println(prop.getProperty("dbpassword"));

} 
catch (IOException ex) {
    ex.printStackTrace();
}

ResourceBundle클래스를 사용 하여 속성 파일을 읽을 수 있습니다 .

ResourceBundle rb = ResourceBundle.getBundle("myProp.properties");

Properties prop = new Properties();

try {
    prop.load(new FileInputStream("conf/filename.properties"));
} catch (IOException e) {
    e.printStackTrace();
}

conf/filename.properties 프로젝트 루트 디렉토리에 기반


키워드는 다음과 같이 사용할 수 없습니다.

props.load(this.getClass().getResourceAsStream("myProps.properties"));

정적 컨텍스트에서.

가장 좋은 방법은 다음과 같은 애플리케이션 컨텍스트를 확보하는 것입니다.

ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/META-INF/spring/app-context.xml");

그런 다음 클래스 경로에서 리소스 파일을로드 할 수 있습니다.

//load a properties file from class path, inside static method
        prop.load(context.getClassLoader().getResourceAsStream("config.properties"));

이것은 정적 및 비 정적 컨텍스트 모두에서 작동하며 가장 중요한 부분은이 속성 파일이 응용 프로그램의 클래스 경로에 포함 된 모든 패키지 / 폴더에있을 수 있다는 것입니다.


파일은 com/example/foo/myProps.properties클래스 경로에서 와 같이 사용할 수 있어야합니다 . 그런 다음 다음과 같이로드하십시오.

props.load(this.getClass().getResourceAsStream("myProps.properties"));

파일 이름이 정확하고 파일이 실제로 클래스 경로에 있는지 확인하십시오. getResourceAsStream()마지막 줄이 예외를 throw하는 경우가 아니면 null을 반환합니다.

myProp.properties가 프로젝트의 루트 디렉토리에있는 경우 /myProp.properties대신 사용하십시오.


java.io.InputStream을 사용하여 아래와 같이 파일을 읽을 수 있습니다.

InputStream inputStream = getClass().getClassLoader().getResourceAsStream(myProps.properties); 

컨텍스트를 loader.getResourceAsStream("myPackage/myProp.properties")사용해야합니다.

행간 '/'ClassLoader.getResourceAsStream(String)메소드에서 작동하지 않습니다 .

Alternatively you could use Class.getResourceAsStream(String) method, which uses '/' to determine if the path is absolute or relative to the class location.

Examples:

myClass.class.getResourceAsStream("myProp.properties")
myClass.class.getResourceAsStream("/myPackage/myProp.properties")

if your config.properties is not in src/main/resource directory and it is in root directory of the project then you need to do somethinglike below :-

Properties prop = new Properties();          
File configFile = new File(myProp.properties);
InputStream stream = new FileInputStream(configFile);
prop.load(stream);

For Reading Properties file with its original order:

    File file = new File("../config/edc.properties");
    PropertiesConfiguration config = new PropertiesConfiguration();
    PropertiesConfigurationLayout layout = new PropertiesConfigurationLayout(config);
    layout.load(new InputStreamReader(new FileInputStream(file)));

    for(Object propKey : layout.getKeys()){
        PropertiesConfiguration propval =  layout.getConfiguration();
        String value = propval.getProperty((String) propKey).toString();
        out.print("Current Key:" + propkey + "Current Value:" + propval + "<br>");
    }

None of the current answers show the InputStream being closed (this will leak a file descriptor), and/or don't deal with .getResourceAsStream() returning null when the resource is not found (this will lead to a NullPointerException with the confusing message, "inStream parameter is null"). You need something like the following:

String propertiesFilename = "server.properties";
Properties prop = new Properties();
try (var inputStream = getClass().getClassLoader().getResourceAsStream(propertiesFilename)) {
    if (inputStream == null) {
        throw new FileNotFoundException(propertiesFilename);
    }
    prop.load(inputStream);
} catch (IOException e) {
    throw new RuntimeException(
                "Could not read " + propertiesFilename + " resource file: " + e);
}

If your properties file path and your java class path are same then you should this.

For example:

src/myPackage/MyClass.java

src/myPackage/MyFile.properties

Properties prop = new Properties();
InputStream stream = MyClass.class.getResourceAsStream("MyFile.properties");
prop.load(stream);

Many answers here describe dangerous methods where they instantiate a file input stream but do not get a reference to the input stream in order to close the stream later. This results in dangling input streams and memory leaks. The correct way of loading the properties should be similar to following:

    Properties prop = new Properties();
    try(InputStream fis = new FileInputStream("myProp.properties")) {
        prop.load(fis);
    }
    catch(Exception e) {
        System.out.println("Unable to find the specified properties file");
        e.printStackTrace();
        return;
    }

Note the instantiating of the file input stream in try-with-resources block. Since a FileInputStream is autocloseable, it will be automatically closed after the try-with-resources block is exited. If you want to use a simple try block, you must explicitly close it using fis.close(); in the finally block.


Specify the path starting from src as below:

src/main/resources/myprop.proper

참고URL : https://stackoverflow.com/questions/8285595/reading-properties-file-in-java

반응형