Jar안에 있는 resource파일 읽기
내가 만든 코드 기능 중에 classpath안에 있는 resource를 읽어들이는 기능이 있었다.(server.config.json을 읽는다.)
그런데 그 프로젝트를 Jar(Executable jar) 로 묶은 후 실행을 하니, resource를 찾을 수 없다는 에러가 났다. (IDE에서는 오류 안남)
=> java.io.FileNotFoundException
자세한 로그는 아래와 같다.
file:/C:/workspace/web-server-project/target/web-server-project-0.0.1-SNAPSHOT.jar!server.config.json
java.io.FileNotFoundException: class path resource [server.config.json] cannot be resolved to absolute file path because it does not reside in the file system.
구글링을 해보니 종종 springBoot쪽에서도 나는 에러인거 같다. springBoot가 jar 라서 그런듯하다.
getClass().getURL() 또는 getClass().getClassLoader().getURL() 을 사용해서 해결하라는 방법이 많이있지만, 이 방법으로도 잘 해결이 안되었다.
=> jar파일에서 실행가능하게 하면 IDE에서 오류가나고, IDE에서 실행가능하게하면 jar로 묶은 후 실행하면 에러가 나는 그런 상황이였음
원래 코드는 아래와 같다. Spring의 ResourceUtils를 사용하였다. (json 파일을 읽어들여 parsing 함)
obj = parser.parse(new FileReader(ResourceUtils.getFile("classpath:" + filePath)));
JSONObject jsonObject = (JSONObject)obj;
setBasicConfig(jsonObject);
log.debug("filePath : {}", filePath);
구글에 여러가지 해결책이 있지만, inputStream을 얻어 사용하는 방법으로 해결하였다.
ClassPathResource classPathResource = new ClassPathResource(filePath);
if(classPathResource.exists() == false){
log.error("Invalid filePath : {}", filePath);
throw new IllegalArgumentException();
}
JSONObject jsonObject = (JSONObject) parser.parse(new InputStreamReader(classPathResource.getInputStream(), "UTF-8"));
cs
ClassPathResource를 사용하면 해당 resource의 inputStream을 얻을 수 있다. (Spring-core lib이다.)
그 inputStream을 활용하는 것이다.
이 방법을 사용하면 IDE와 Jar로 묶었을 때, 둘다 오류가 나지 않는다.
아직 시간이 없어서 자세히 오류가 왜나는지 정확한 해결책은 뭔지에 대해서 알지 못하였지만, 조만간 찾아봐서 올려야겠다.
'프로그래밍 노트 > 트러블슈팅' 카테고리의 다른 글
[Mybatis] 동적 쿼리 DBMS별 Like 문 (0) | 2019.07.12 |
---|---|
[Maven] error resolving version for plugin from the repositories ... 오류 (0) | 2019.03.26 |
AES256 암호화시 java.security.InvalidKeyException: Illegal key size 해결방안 (3) | 2019.03.06 |
[SVN] Working copy is not up-to-date 해결 (0) | 2018.06.18 |
[RSA] pem에서 RSA 개인키를 얻으려고할 때 InvalidKeySpecException (0) | 2018.06.15 |