문제
내 패키지 구조에 묻힌 속성 파일을 읽어야합니다. com.al.common.email.templates
.
나는 모든 것을 시도했고 그것을 알아낼 수는 없습니다.
결국 내 코드는 서블릿 컨테이너로 실행되지만 컨테이너에 의존하고 싶지는 않습니다. 나는 주니트 테스트 케이스를 작성하고 두 가지 모두에서 작동해야합니다.
해결책
패키지의 클래스에서 속성을로드 할 때 com.al.common.email.templates
당신이 사용할 수있는
Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("foo.properties");
prop.load(in);
in.close();
(필요한 모든 예외 처리를 추가하십시오).
수업이 해당 패키지에 있지 않은 경우 입력 스트림을 약간 다르게 아키셔야합니다.
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.java
그리고 TestLoadProperties.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());
}
}
}
사용한다고 가정합니다 속성 클래스를 통해 짐 방법, 클래스 로더를 사용하고있는 것 같아요 getResourceasstream 입력 스트림을 얻으려면.
이름을 어떻게 전달하고 있습니까?이 형태로되어 있어야합니다. /com/al/common/email/templates/foo.properties
이 전화 로이 문제를 해결했습니다
Properties props = PropertiesUtil.loadProperties("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();
}
}