Java IO流 --- 文件拷贝方法封装

本文介绍了一个简单的Java程序,用于实现文件的复制功能。通过使用FileInputStream和FileOutputStream,该工具能够将一个文件完整地复制到另一个位置。文章包含了完整的代码示例及异常处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUtil {
	/**
	 * 
	 * @param scrPath 数据源路径
	 * @param destPath 拷贝目标路径
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static void copyFile(String scrPath,String destPath) throws FileNotFoundException,IOException {
		//建立联系
	//	File src = new File(scrPath);//数据源 存在且为文件
	//	File dest = new File(destPath);//写入目的地 文件可以不存在
		copyFile(new File(scrPath), new File(destPath));
	}	
	/**
	 * 
	 * @param scrPath 数据源对象
	 * @param destPath 拷贝目标对象
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static void copyFile(File src,File dest) throws FileNotFoundException,IOException {

		if (!src.isFile()) {
			System.out.println("只能拷贝文件");
			throw new IOException("只能拷贝文件");
		}
		//选择流
		InputStream is = new FileInputStream(src);
		OutputStream os = new FileOutputStream(dest);
		//文件拷贝  读取+写入
		byte[] flush = new byte[1024];//接收字节数组
		int len = 0;//定义接收长度
		//循环读取 每次读取长度len,有数据则循环读取,没有数据后结束循环
		while(-1!=(len=is.read(flush))){
			//写入 将字节数组flush从0写入
			os.write(flush, 0, len);
		}
		os.flush();
		//关闭流,先打开的后关闭
		os.close();
		is.close();
		
	}	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值