본문 바로가기

Java/예제

예외, 에러처리 try-with-resource문 예제

import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {

        try (FileOutputStream out = new FileOutputStream("test.txt")) {
            // test.txt file 에 Hello Sparta 를 출력
            out.write("Hello Sparta".getBytes());
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

형식은 try-catch문과 비슷하지만, try()안에 AutoClosable 인터페이스를 구현한 객체를 선언하면 사용할 수 있다!

'Java > 예제' 카테고리의 다른 글

컬렉션 - Map  (0) 2022.11.16
컬렉션-Set  (0) 2022.11.16
컬렉션-리스트  (0) 2022.11.16
날짜와 시간 퀴즈  (0) 2022.11.16
예외,에러 처리 try-catch-finally 예제  (0) 2022.11.15