2015년 11월 18일 수요일

try with resources

자바 7에 추가된 try-with-resources 구문이라는 것이 있다.
이전에 사용되어 왔던, 아래의 finally에 들어가는 close 메서드를 자동으로 해주는 기능이다.



사용되는 resource 중 java.lang.AutoCloseable 을 implement 하는 객체에서 사용되어질 수 있다.

자세한 예는 아래와 같다.

static String readFirstLineFromFileWithFinallyBlock(String path)
                                                     throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
    }
}
public static void writeToFileZipFileContents(String zipFileName,
                                           String outputFileName)
                                           throws java.io.IOException {

    java.nio.charset.Charset charset =
         java.nio.charset.StandardCharsets.US_ASCII;
    java.nio.file.Path outputFilePath =
         java.nio.file.Paths.get(outputFileName);

    // Open zip file and create output file with
    // try-with-resources statement

    try (
        java.util.zip.ZipFile zf =
             new java.util.zip.ZipFile(zipFileName);
        java.io.BufferedWriter writer =
            java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
    ) {
        // Enumerate each entry
        for (java.util.Enumeration entries =
                                zf.entries(); entries.hasMoreElements();) {
            // Get the entry name and write it to the output file
            String newLine = System.getProperty("line.separator");
            String zipEntryName =
                 ((java.util.zip.ZipEntry)entries.nextElement()).getName() +
                 newLine;
            writer.write(zipEntryName, 0, zipEntryName.length());
        }
    }
}

원본 출처 : https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

댓글 없음 :

댓글 쓰기