[Spring] jar 배포시 파일 처리 에러

yeonjoo913·2023년 6월 19일
0

Spring

목록 보기
3/19

에러 메세지

IOExceptionclass path resource [mail.html] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:  ~~ /mail.html
  • jar:file:경로~ 로 실행하게 되어 Exception이 발생

  • Local 환경에서는 파일 처리를 하는데 문제가 없는데, 개발 배포를 하면 위와 같은 에러가 발생한다. 현재 개발서버는 jar로 배포를 하고 있다.

원인 코드

File file = new ClassPathResource("mail.html").getFile();

springboot를 통해서 jar 파일로 만들게 될 경우, class file,resource 등을 하나로 합친 jar파일 한개가 생성된다. 이때 jar파일의 프로토콜은 jar: 시작하게 된다. 즉 IDE에서의 file 시스템과 경로가 다르다.

  • 로컬 IDE 환경 : file://로 시작(실제 파일시스템으로 접근)
  • jar 실행 환경 : jar:file: 로 시작

그렇다면, jar파일로 패키징 했을 때 resource를 file로 받아올 수 있는 방법이 없을까??
=> resource를 InputStream으로 리턴받아서 사용하면된다.

변경 후 코드

InputStream inputStream = new ClassPathResource("mail.html").getInputStream();
File file = File.createTempFile("mail",".html");
FileUtils.copyInputStreamToFile(inputStream,file);
profile
주니어 백엔드 개발자. 까먹는다 기록하자!

0개의 댓글