[Java] jar 파일 내 resources 읽기 - ClassPathResource

ITWeb/개발일반 2020. 7. 21. 20:23

제목에 있는 그대로 입니다.

 

[참고문서]

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/io/ClassPathResource.html

 

ClassPathResource 를 이용해서 구현 하면 됩니다.

// resourceFile 은 resources 를 제외한 path 와 filename 을 작성 합니다.

ClassPathResource resource = new ClassPathResource(resourceFile);

 

아래 예제 코드는 programcreek.com 에서 가져 왔습니다.

public static String getResourceAsString(String path) {
	try {
		Resource resource = new ClassPathResource(path);
		try (BufferedReader br = new BufferedReader(
				new InputStreamReader(resource.getInputStream()))) {
			StringBuilder builder = new StringBuilder();
			String line;
			while ((line = br.readLine()) != null) {
				builder.append(line).append('\n');
			}
			return builder.toString();
		}
	}
	catch (IOException e) {
		throw new IllegalStateException(e);
	}
}

이와 같이 구현을 한 이유는 로컬에서는 잘 되는데 jar 로 말았을 때는 file 을 찾지 못하는 에러가 발생을 해서 입니다.

: