728x90
반응형
try-catch-finally
//서버 소켓 준비
ServerSocket serverSocket = new ServerSocket(5555);
for (int i = 0; i < 100; i++) {
Socket client = null;
InputStream fin = null;
OutputStream out = null;
try{
//연결 받기
client = serverSocket.accept();
System.out.println(client);
//파일 InputStream 연결
fin = new FileInputStream("C:\\파일위치");
//OutputStream 뽑기
out = client.getOutputStream();
//읽고 쓰기
byte[] buffer = new byte[1024*8];
while(true){
int count = fin.read(buffer);
System.out.println(count);
if(count == -1){ break; }
out.write(buffer,0, count);
}
fin.close();
fin = null;
out.close();
out = null;
client.close();
client = null;
}catch (Exception e){
e.printStackTrace();
}finally {
System.out.println("finally.....");
//닫기
if(client != null) try { client.close();}catch ( Exception e){}
if(fin != null) try { fin.close();}catch ( Exception e){}
if(out != null) try { out.close();}catch ( Exception e){}
}
}//for end
//닫기
serverSocket.close();
try에서 inputStream 객체 생성 finally에서 close해준다.
try 안의 코드를 실행하다 Exception이 발생하는 경우 모든 코드가 실행되지 않을 수 있기 때문에 finally에 close 코드를 넣어주어야 한다.
InputStream 객체가 null인지 체크해줘야 하며 close에 대한 Exception 처리도 해야한다.
try with resources
ServerSocket serverSocket = new ServerSocket(5555);
for (int i = 0; i < 100; i++) {
try(Socket client = serverSocket.accept();
InputStream fin = new FileInputStream("C:\\파일위치");
OutputStream out = client.getOutputStream();
//Autocloseable 타입만 들어갈 수 있다.
){
//읽고 쓰기
byte[] buffer = new byte[1024*8];
while(true){
int count = fin.read(buffer);
if(count == -1){ break; }
out.write(buffer,0, count);
}
}catch (Exception e){
e.printStackTrace();
}
}//for end
//닫기
serverSocket.close();
try(...)안에서 사용할 InputStream 객체 선언 및 할당
코드의 실행 위치가 try 문을 벗어나면 try-with-resources는 try(...)안에 선언된 객체의 close() 메소드를 호출해야 하므로 finally에 호출할 필요가 없다.
try-with-resources에서 자동으로 close가 호출되는 것은 AutoCloseable을 구현한 객체에만 해당이 된다.
try-with-resources의 장점
- 간결하고 짧은 코드.
- 가독성이 높아짐.
- 많은 try-catch 사용으로 close를 빼먹는 실수의 가능성이 줄어듬.
lombok @cleanup
자동 자원 닫기
IO 처리 시 try-catch-finally 문의 finally 절을 통해서 close() 메소드를 호출을 간단하게 하는 지원.
@Cleanup 어노테션을 사용하면 해당 자원이 자동으로 닫힘.
@Cleanup InputStream inputStream = socket.getInputStream();
반응형
'JAVA_기초 공부' 카테고리의 다른 글
[JAVA] 멀티쓰레딩이란 (0) | 2023.02.17 |
---|---|
[JAVA] Enum 으로 Singleton만들기 (0) | 2023.02.17 |
[JAVA] Override / Overloading (0) | 2023.02.15 |
[JAVA] Getter/Setter (0) | 2023.02.15 |
[JAVA] 자바의 변수/함수 (0) | 2023.02.15 |