관리 메뉴

IT.FARMER

JAVA try catch with resource 본문

JAVA

JAVA try catch with resource

아이티.파머 2016. 3. 15. 21:05
반응형

우리는 자바를 사용하여 파일 입출력을 사용할때.

finally 에 항상 close() 하는 구문을 선언하여 메모리가 엉뚱한데 잡고 있지 않도록 하였다.

 

이런 기능이 왜 생기지 않았을까 ? 하는 생각이 들때쯤

Web Application Service 를 만들라과제를 하던중에 try catch with resource 라는것을 접하게 되었고,

 

WoW 이런 기능이!!

 

try (  ...   ) 안에 선언하여 finally 에서 자원을 닫아주지 않아도 자동으로 해당 자원을 close()시켜준다.

 

공식 문서 참조 :

https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

 

protected static boolean fileWriteStream(FTPClient client, 
   String remoteFilePath,
   String remoteFileName,
   String localFilePath,
   String localFileName) {
   byte bytesArray[] = new byte[4096];
   
    try (InputStream inputStream =  client.retrieveFileStream(remoteFilePath + "/" + remoteFileName );
    OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(localFilePath + "/" + localFileName));
    ){

      int bytesRead = -1;
      while ((bytesRead=inputStream.read(bytesArray)) != -1) {
      	outputStream.write(bytesArray, 0, bytesRead);
      }
    } catch (IOException e) {
		logger.error("File write fail", e);
	return false;
	} 
	return true;
 }

 

 

 

 

 

반응형