0
点赞
收藏
分享

微信扫一扫

复制文件异常处理,3种方式(JDK9、JDK7、标准)

Python芸芸 2022-02-12 阅读 77
java
package glj10;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class ExceptionDemo {
    public static void main(String[] args) {
        
    }
    
    //JDK9的改进方案
    public static void method2() throws IOException{
        FileReader fr = new FileReader("e:\\share\\java.txt");
        FileWriter fw = new FileWriter("E:\\share\\java111.txt");
        try(fr;fw){

            char[] chs = new char[1024];
            int len;
            while ((len = fr.read(chs))!=-1){
                fw.write(chs,0,len);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        
    }
    
    //JDK7的改进方案,try catch 无finally
    public static void method1(){
        
        try(FileReader fr = new FileReader("e:\\share\\java.txt");
            FileWriter fw = new FileWriter("E:\\share\\java111.txt");){
            
            char[] chs = new char[1024];
            int len;
            while ((len = fr.read(chs))!=-1){
                fw.write(chs,0,len);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        
        
//        fw.close();
//        fr.close();
//        
        
    }
    //标准方案try catch finally
    public static void method(){
        FileReader fr=null;
        FileWriter fw=null;
        try{
            fr= new FileReader("e:\\share\\java.txt");
            fw= new FileWriter("E:\\share\\java111.txt");
            char[] chs = new char[1024];
            int len;
            while ((len = fr.read(chs))!=-1){
                fw.write(chs,0,len);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (fr!=null){
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fw!=null){
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    
}
举报

相关推荐

0 条评论