不同JDK版本的流异常处理

1、JDK7以前的流异常try-catch处理

    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("D:\\1.txt");
            int len;
            while ((len = fis.read()) != -1){
                System.out.println((char) len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

2、JDK7新特性 流异常try-catch处理

public static void main(String[] args) {
        try(FileInputStream fis = new FileInputStream("D:\\1.txt");
            FileOutputStream fos = new FileOutputStream("D:\\2.txt")){
            int len;
            while ((len = fis.read()) != -1){
                System.out.println((char) len);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

3、JDK9新特性 流异常try-catch处理

    public static void main(String[] args) throws FileNotFoundException {
        FileInputStream fis = new FileInputStream("D:\\1.txt");
        FileOutputStream fos = new FileOutputStream("D:\\2.txt");
        try(fis;fos){
            int len;
            while ((len = fis.read()) != -1){
                System.out.println((char) len);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

  

posted @ 2021-02-23 17:25  是今  阅读(115)  评论(0编辑  收藏  举报