String fileName = "file.xlsx"
FileInputStream fis = null
try {
String path = ResourceUtils.getFile("classpath:" + fileName).getPath();
File file = new File(path);
int size = (int)file.length();
fis = new FileInputStream(path);
...
} catch (Exception E) {
...
} finally {
if (fis != null) {
fis.clos();
}
}
resource 폴더 아래에 저장한 파일을 다운로드 하는 부분이다.
톰캣으로 로컬에서 실행할 때는 정상적으로 파일을 가져오던 부분이 wildfly deploy 하니 아래와 같은 에러 로그가 떴다.
class path resource [fileName.xlsx] cannot be resolved to absolute file path because it dose not reside in the file system: vfs:/content/web.war/WEB-INF/classes/fileName.xlsx
확인 결과 wildfly는 VFS(Virtual File System)을 사용하기 때문에 url을 가져와도 실제 경로가 아니므로 그 경로로 파일을 가져오는 것이 불가능하다. 때문에 stream을 사용하여 파일에 접근해야 한다.
String fileName = "file.xlsx"
InputStream resource= null
try {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
resource = classLoader.getResourceAsStream(fileName);
int fSize = resource.available();
...
int readCount = 0;
byte[] buffer = new byte[1024];
while((readCount = resource.read(buffer)) != -1){
out.write(buffer,0,readCount);
}
...
} catch (Exception E) {
...
} finally {
if (fis != null) {
fis.clos();
}
}
getResourceAsStream을 사용하여 위와 같이 수정 배포하니 정상적으로 다운로드 되었다!