[java] Java 패키지에서 속성 파일로드

내 패키지 구조에 묻혀있는 속성 파일을 읽어야합니다 com.al.common.email.templates.

나는 모든 것을 시도했지만 알아낼 수 없습니다.

결국 내 코드는 서블릿 컨테이너에서 실행되지만 컨테이너에 의존하고 싶지는 않습니다. JUnit 테스트 케이스를 작성하고 두 가지 모두에서 작동해야합니다.



답변

패키지의 클래스에서 속성을로드 할 때 com.al.common.email.templates다음을 사용할 수 있습니다.

Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("foo.properties");
prop.load(in);
in.close();

(필요한 예외 처리를 모두 추가하십시오).

클래스가 해당 패키지에없는 경우 InputStream을 약간 다르게 획득해야합니다.

InputStream in = 
 getClass().getResourceAsStream("/com/al/common/email/templates/foo.properties");

상대 경로 (없는 사람 선도적 인 ‘/’)에서 getResource()/ getResourceAsStream()평균 자원 클래스에 패키지를 나타내는 디렉토리를 기준으로 검색됩니다.

를 사용 하면 클래스 경로 java.lang.String.class.getResource("foo.txt")에서 (존재하지 않는) 파일 /java/lang/String/foo.txt을 검색합니다 .

절대 경로 ( ‘/’로 시작하는 경로)를 사용하면 현재 패키지가 무시됩니다.


답변

Joachim Sauer의 답변에 추가하려면 정적 컨텍스트에서이 작업을 수행해야하는 경우 다음과 같은 작업을 수행 할 수 있습니다.

static {
  Properties prop = new Properties();
  InputStream in = CurrentClassName.class.getResourceAsStream("foo.properties");
  prop.load(in);
  in.close()
}

(전과 같이 예외 처리가 생략되었습니다.)


답변

다음 두 경우는라는 예제 클래스에서 속성 파일을로드하는 것과 관련이 TestLoadProperties있습니다.

사례 1 : 다음을 사용하여 속성 파일로드 ClassLoader

InputStream inputStream = TestLoadProperties.class.getClassLoader()
                          .getResourceAsStream("A.config");
properties.load(inputStream);

이 경우 root/src성공적으로로드 하려면 속성 파일이 디렉터리에 있어야합니다 .

사례 2 : 사용하지 않고 속성 파일로드 ClassLoader

InputStream inputStream = getClass().getResourceAsStream("A.config");
properties.load(inputStream);

이 경우 TestLoadProperties.class성공적으로로드 하려면 속성 파일이 파일과 동일한 디렉토리에 있어야합니다 .

참고 : TestLoadProperties.javaTestLoadProperties.class두 개의 다른 파일입니다. 전자의 .java파일은 일반적으로 프로젝트의 src/디렉토리에 있고 후자의 .class파일은 일반적으로 해당 bin/디렉토리에 있습니다.


답변

public class Test{  
  static {
    loadProperties();
}
   static Properties prop;
   private static void loadProperties() {
    prop = new Properties();
    InputStream in = Test.class
            .getResourceAsStream("test.properties");
    try {
        prop.load(in);
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}


답변

public class ReadPropertyDemo {
    public static void main(String[] args) {
        Properties properties = new Properties();

        try {
            properties.load(new FileInputStream(
                    "com/technicalkeeda/demo/application.properties"));
            System.out.println("Domain :- " + properties.getProperty("domain"));
            System.out.println("Website Age :- "
                    + properties.getProperty("website_age"));
            System.out.println("Founder :- " + properties.getProperty("founder"));

            // Display all the values in the form of key value
            for (String key : properties.stringPropertyNames()) {
                String value = properties.getProperty(key);
                System.out.println("Key:- " + key + "Value:- " + value);
            }

        } catch (IOException e) {
            System.out.println("Exception Occurred" + e.getMessage());
        }

    }
}


답변

Load 메서드 를 통해 Properties 클래스를 사용한다고 가정 하고 ClassLoader getResourceAsStream 을 사용 하여 입력 스트림을 가져 오고 있다고 가정합니다 .

이름을 어떻게 전달하고 있습니까? 다음과 같은 형식이어야합니다. /com/al/common/email/templates/foo.properties


답변

이 전화로이 문제를 해결했습니다.

Properties props = PropertiesUtil.loadProperties("whatever.properties");

추가로, whatever.properties 파일을 / src / main / resources에 넣어야합니다.