IO-文件的拷贝标准代码

package cn.text.one;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Snippet {
	public static void main(String[] args) {
	        //将a.txt内容拷贝到b.txt
	        copyFile("abc.txt", "abc2.txt"); 
	    }
	    /**
	     * 将src文件的内容拷贝到dec文件
	     * @param src 源文件
	     * @param dec 目标文件
	     */
	    static void copyFile(String src, String dec) {
	        FileInputStream fis = null;
	        FileOutputStream fos = null;
	        //为了提高效率,设置缓存数组!(读取的字节数据会暂存放到该字节数组中)
	        byte[] buffer = new byte[1024];
	        int temp = 0;
	        try {
	            fis = new FileInputStream(src);
	            fos = new FileOutputStream(dec);
	            //边读边写
	            //temp指的是本次读取的真实长度,temp等于-1时表示读取结束
	            while ((temp = fis.read(buffer)) != -1) {
	                /*将缓存数组中的数据写入文件中,注意:写入的是读取的真实长度;
	                 *如果使用fos.write(buffer)方法,那么写入的长度将会是1024,即缓存
	                 *数组的长度*/
	                fos.write(buffer, 0, temp);
	            }
	        } catch (Exception e) {
	            e.printStackTrace();
	        } finally {
	            //两个流需要分别关闭
	            try {
	                if (fos != null) {
	                    fos.close();
	                }
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	            try {
	                if (fis != null) {
	                    fis.close();
	                }
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	    }
}


在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值