Java如何实现文件拷贝操作和如何正确关闭资源

http://blog.csdn.net/caidie_huang/article/details/52738225

使用字节流完成文件的拷贝:
使用字节输入流(FileInputStream)将源文件中的数据读进来,同时使用字节输出流(FileOutputStream)将读进来的数据写到目标文件中,即一边读一边写,完成文件的拷贝

//使用字节流完成文件的拷贝操作  
public class FileStremCopyDemo {  
    public static void main(String[] args) throws IOException {  
        //创建目标与源对象  
        File srcFile = new File("file/src.txt");//源对象  
        File desFile = new File("file/des.txt");//目标文件  

        //创建输入输出流  
        InputStream in = new FileInputStream(srcFile);  
        OutputStream out = new FileOutputStream(desFile);  

        //IO 操作  
        byte[] buffer = new byte[1024];//创建容量为1024的缓冲区(存储已经读取的字节数据)  
        int len = -1;//表示已经读取了多少个字节数据,若果等于-1,表示已经读到最后  
        while((len = in.read(buffer)) != -1){  
            //数据在buffer数组中  
            out.write(buffer, 0, len);  
        }  
        //关闭资源  
        in.close();  
        out.close();  
    }  

}  

上面程序实现文件的拷贝中,是直接将异常抛出去,一般这种情况是要处理异常的,按正常的try catch处理异常,我们会发现关闭资源的代码会很繁琐,如下:

//繁琐的资源关闭方式  
private static void test1() {  
    File srcFile = new File("file/src.txt");  
    File desFile = new File("file/des.txt");  

    InputStream in = null;  
    OutputStream  out = null;  
    try {  
        in = new FileInputStream(srcFile);  
        out = new FileOutputStream(desFile);  

        byte[] buffer = new byte[1024];  
        int len = -1;  

        while ((len = in.read(buffer)) != -1) {  
            out.write(buffer);  
        }  

    } catch (FileNotFoundException e) {  
        e.printStackTrace();  
    } catch (IOException e) {  
        e.printStackTrace();  
    } finally {  
        try {  
            if (in != null) {  
                in.close();  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  

        if (out != null) {  
            try {  
                out.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
}  

从Java7开始,Java新添了一个特性,在try后面加上一个圆括号,将需要关闭的资源放到里面定义,程序执行完毕会自动帮我们关闭圆括号里面的资源,如下:

//Java7自动关闭资源  
private static void test2() {  
    File srcFile = new File("file/src.txt");  
    File desFile = new File("file/des.txt");  

    try (  
            InputStream in = new FileInputStream(srcFile);  
            OutputStream out = new FileOutputStream(desFile);  
            ) {  

        byte[] buffer = new byte[1024];  
        int len = -1;  

        while ((len = in.read(buffer)) != -1) {  
            out.write(buffer);  
        }  

    }catch (IOException e) {  
        e.printStackTrace();  
    }  

}  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值