developer tip

Java 패키지에서 특성 파일로드

optionbox 2020. 8. 3. 08:28
반응형

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에 넣어야합니다.


클래스 패키지를 처리 ​​할 필요가없는 위의 것보다 유사하지만 훨씬 간단한 솔루션을 언급하는 사람은 없습니다. myfile.properties가 클래스 경로에 있다고 가정하십시오.

        Properties properties = new Properties();
        InputStream in = ClassLoader.getSystemResourceAsStream("myfile.properties");
        properties.load(in);
        in.close();

즐겨


아래 코드를 사용하십시오 :

    Properties p = new Properties(); 
    StringBuffer path = new StringBuffer("com/al/common/email/templates/");
    path.append("foo.properties");
    InputStream fs = getClass().getClassLoader()
                                    .getResourceAsStream(path.toString());

if(fs == null){ System.err.println("Unable to load the properties file"); } else{ try{ p.load(fs); } catch (IOException e) { e.printStackTrace(); } }

참고URL : https://stackoverflow.com/questions/333363/loading-a-properties-file-from-java-package

반응형