2009-07-07 3 views
8

ClassLoader를 사용하여 Properties 클래스의 속성 파일을로드하려고합니다. 나는 "theta.properties"파일이이 클래스와 같은 디렉토리에서Java ClassLoader를 사용하여 클래스 경로에서 파일을로드하는 방법은 무엇입니까?

loader = this.getClass().getClassLoader(); 
in = loader.getResourceAsStream("theta.properties"); 
result = new Properties(); 
result.load(in); 

를하지만의 InputStream는 항상 null의 :이 토론의 목적을 위해 처리 오류를 제거하려면 아래의 코드를 단순화했습니다. 파일을 틀린 장소에두고 있습니까? 이클립스와 그 세트를 사용하여 클래스 파일을 소스 폴더에 빌드하므로 문제가되지 않아야합니다.

JavaDoc에서 ClassLoader가 어떤 클래스 경로를 검색하는지 알 수없는 항목이 있습니다.

답변

10

루트 경로 디렉토리에서 "theta.properties"을 찾아 getClass().getClassloader()를 사용하여. 해당 클래스에 상대적인 리소스를 얻으려면 getClass().getResourceAsStream()을 사용하면됩니다.

6

파일이 클래스와 동일한 디렉토리에 있으면 클래스의 패키지 앞에 디렉토리를 추가해야합니다.

그래서 패키지 인 경우 :

package com.foo.bar; 

그런 다음 코드는 다음과 같습니다

.getResourceAsStream("com/foo/bar/theta.properties"); 
-1

ResourceBundle을 사용할 수 있습니다.

관련 문제