[Java 개발의 길] (20)try-with-resource 예외 선언

59319 단어 java 개발의 길
Try-with-resources는java7의 새로운 비정상 처리 메커니즘으로try-catch 문장 블록에서 사용하는 자원을 쉽게 닫을 수 있습니다.
java7 이전에 프로그램에서 사용한 자원은 명확하게 닫혀야 하기 때문에 과정이 좀 번거롭다. 아래와 같다.

  
  
  
  
  1. package com.qunar.lectures.tryResource;
  2. import java.io.*;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. /**
  6. * Created by xiaosi on 16-3-4.
  7. */
  8. public class TryResourceDemo {
  9.    //
  10.    public static List<String> readLines(String resourcePath) {
  11.        String path = TryResourceDemo.class.getResource(resourcePath).getPath();
  12.        File file = new File(path);
  13.        if (!file.exists()) {
  14.            throw new RuntimeException("Can not find file + " + resourcePath);
  15.        }//if
  16.        if (!file.isFile()) {
  17.            throw new RuntimeException(resourcePath + " is not a regular file");
  18.        }//if
  19.        FileInputStream fis;
  20.        InputStreamReader isr;
  21.        BufferedReader br = null;
  22.        try {
  23.            fis = new FileInputStream(file);
  24.            isr = new InputStreamReader(fis, "UTF-8");
  25.            br = new BufferedReader(isr);
  26.            List<String> lines = new ArrayList<String>();
  27.            String line;
  28.            while ((line = br.readLine()) != null) {
  29.                lines.add(line);
  30.            }//while
  31.            return lines;
  32.        }
  33.        catch (IOException e) {
  34.            throw new RuntimeException("Read file failed , file=" + resourcePath, e);
  35.        }
  36.        finally {
  37.            if(br != null){
  38.                try {
  39.                    br.close();
  40.                } catch (IOException e) {
  41.                    e.printStackTrace();
  42.                }
  43.            }//if
  44.        }//finally
  45.    }
  46.    public static void main(String[] args) {
  47.        List<String> lines = readLines("/a.txt");
  48.        for(String line : lines){
  49.            System.out.println("line:" + line);
  50.        }//for
  51.    }
  52. }


try , finally 。 finally 。 ? try , finally 。


  
  
  
  
  1. private static void printFileJava7() throws IOException {
  2.    try(FileInputStream input = new FileInputStream("file.txt")) {
  3.        int data = input.read();
  4.        while(data != -1){
  5.            System.out.print((char) data);
  6.            data = input.read();
  7.        }
  8.    }
  9. }


  
  
  
  
  1. try(FileInputStream input = new FileInputStream("file.txt")) {

try-with-resource 。FileInputStream try 。 , 。 try ,FileInputStream 。 FileInputStream java java.lang.AutoCloseable 。 try-with-resources 。

try-with-resources , FileInputStreami ( close ) ,try-with-resources , FileInputStreami 。 ( finally ) 。

JDK7 AutoCloseable Closeable try-with-resource


  
  
  
  
  1. package com.qunar.lectures.tryResource;
  2. import java.io.*;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. /**
  6. * Created by xiaosi on 16-3-4.
  7. */
  8. public class TryResourceDemo {
  9.    //
  10.    public static List<String> readLines(String resourcePath) {
  11.        String path = TryResourceDemo.class.getResource(resourcePath).getPath();
  12.        File file = new File(path);
  13.        if (!file.exists()) {
  14.            throw new RuntimeException("Can not find file + " + resourcePath);
  15.        }//if
  16.        if (!file.isFile()) {
  17.            throw new RuntimeException(resourcePath + " is not a regular file");
  18.        }//if
  19.        // try-with-resource
  20.        try (FileInputStream fis = new FileInputStream(file);
  21.             InputStreamReader isr = new InputStreamReader(fis);
  22.                BufferedReader br = new BufferedReader(isr)){
  23.            List<String> lines = new ArrayList<String>();
  24.            String line;
  25.            while ((line = br.readLine()) != null) {
  26.                lines.add(line);
  27.            }//while
  28.            return lines;
  29.        }
  30.        catch (IOException e) {
  31.            throw new RuntimeException("Read file failed , file=" + resourcePath, e);
  32.        }
  33.    }
  34.    public static void main(String[] args) {
  35.        List<String> lines = readLines("/a.txt");
  36.        for(String line : lines){
  37.            System.out.println("line:" + line);
  38.        }//for
  39.    }
  40. }





좋은 웹페이지 즐겨찾기