반응형
    
    
    
  try 만을 사용한 입출력 표현 방법
    /// 전통적으로 자원이 제대로 닫힘을 보장하는 수단으로 try-finally가 쓰였다.
    static String firstLineOfFile(String path) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(path));
        try {
            return br.readLine();
        } finally {
            br.close();
        }
    }
    // 위에 것도 나쁘지 않지만 자원을 하나더 사용한다면 어떨까
    private static final int BUFFER_SIZE = 16;
    static void copy(String src, String dst) throws IOException {
        InputStream in = new FileInputStream(src);
        try {
            OutputStream out = new FileOutputStream(dst);
            try {
                byte[] buf = new byte[BUFFER_SIZE];
                int n;
                while ((n = in.read(buf)) >= 0)
                    out.write(buf, 0, n);
            } finally {
                out.close();
            }
        } finally {
            in.close();
        }
    }try-with-resources를 사용해서 deeps를 줄이고 가독성을 향상
    // try-with-resource 짧고 매혹적이다.
    static String firstLineOfFile(String path) throws IOException {
        try (BufferedReader br = new BufferedReader(
                new FileReader(path)
        )) {
            return br.readLine();
        }
    }
    private static final int BUFFER_SIZE = 16;
    static void copy(String src, String dst) throws IOException {
        try (InputStream in = new FileInputStream(src);
             OutputStream out = new FileOutputStream(src)) {
            byte[] buf = new byte[BUFFER_SIZE];
            int n;
            while ((n = in.read()) >= 0)
                out.write(buf, 0, n);
        }
    }
try - catch 문법 응용
    static String firstLineOFFile(String path, String defaultVal) {
        try (BufferedReader br = new BufferedReader(
                new FileReader(path)
        )) {
            return br.readLine();
        } catch (IOException e) {
            return defaultVal;
        }
    }
핵심정리
꼭 회수해야 하는 자원을 다룰 때는 try-finally 말고 , try-with-resources를 사용하자. 예외는 없다. 코드는 더 짧고 분명해지고, 만들어지는 예외 정보도 훨씬 유용하다. try-finally로 작성하면 실용적이지 못할 만큼 코드가 지저분해지는 경우라도, try-with-resources로는 정확하고 쉽게 자원을 회수할 수 있다.
반응형
    
    
    
  '언어 > JAVA' 카테고리의 다른 글
| 카카오 2차 : JAVA로 JSON 파싱을 해보자! (0) | 2020.09.22 | 
|---|---|
| Servlet API란? Gradle을 이용해서 이클립스에 ServletAPI를 등록 (0) | 2020.08.08 | 
| java : ArrayList : subList, reverse (0) | 2020.05.13 | 
| PS 용 baseCode(추가예정) (0) | 2020.03.07 | 
| 백준 : 15684 (0) | 2020.01.30 | 
 
									
								