JAVA
Try-with-resources
Developer Garam.Choi
2021. 4. 8. 14:15
JAVA 1.7 이상을 쓴다면 Try with resources를 사용할수있다는 내용을 알게되었다.
현재까지는 솔루션 내부 소스든, 구글링에서 보이는 내역들처럼 눈에 띄인 내용이 없어서 알지못했었는데,
알게된 김에 정리.
FileInputStream fis = null;
try {
File pdfFile = new File(fileUploadPath + "fileName.pdf");
fis = new FileInputStream(pdfFile);
byte[] pdfFileBytes = IOUtils.toByteArray(fis);
result.put(Const.RESULT_STATUS, Const.SUCCESS);
} catch (FileNotFoundException fnfe) {
throw new CommonException(this.getClass().getName() + ".fileTest() : fileNotFound", fnfe.getMessage());
} catch (IOException io) {
throw new CommonException(this.getClass().getName() + ".fileTest() : IOException", io.getMessage());
} catch (Exception e){
throw new CommonException(this.getClass().getName() + ".fileTest() : Exception", e.getMessage());
} finally {
try{
if(null != fis) fis.close();
}catch (FileNotFoundException fnfe) {
throw new CommonException(this.getClass().getName() + ".fileTest() : fileNotFound", fnfe.getMessage());
} catch (IOException io) {
throw new CommonException(this.getClass().getName() + ".fileTest() : IOException", io.getMessage());
} catch (Exception e){
throw new CommonException(this.getClass().getName() + ".fileTest() : Exception", e.getMessage());
}
}
우리가 기본적으로 사용하는 패턴은 위와 같이 진행할 경우가 많다.
딱봐도 catch문이 많고, close에 대한 내역을 finally 에서 닫아줘야하기에 번거로운 절차가 있었다.
위와같이 try-with-resource 를 사용하면, Autoclose가 되기때문에, 처리가 가능하다.
현재 사내는 java compile 1.6이기에 사용이 불가..