Java基础回顾 : 利用字节流实现文件的拷贝

本文介绍了一种使用字节流进行文件复制的方法。通过Java编程实现从源文件到目标文件的数据拷贝过程,适用于所有类型的数据文件。

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

本文是一个范例 : 利用字节流实现文件的拷贝

package example;
/**
 * 文件的拷贝.
 */
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class TestDemo {
	public static void main(String[] args) {
		String srcPath = "e:\\test.txt";
		String destPath = "e:\\msg\\info.txt";
		try {
			copyFile(srcPath,destPath);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 利用字节流来实现文件的复制(字节流可以处理一切数据)
	 * @param srcPath : 源文件路径
	 * @param destPath : 目标文件路径
	 * @throws Exception
	 */
	public static void copyFile(String srcPath,String destPath) throws Exception{
		//构建源文件和目标文件的File对象
		File src = new File(srcPath);
		File dest = new File(destPath);
		//如果源文件不存在,抛出异常
		if(!src.exists()){
			throw new IOException("文件不存在!");
		}
		//如果目标文件父路径不存在,创建父路径
		if(!dest.getParentFile().exists()) {
			dest.getParentFile().mkdirs();
		}
		//实例化输入流和输出流
		InputStream is = new FileInputStream(src);
		OutputStream os = new FileOutputStream(dest);
		//定义缓冲字节数组,用来接收读取的内容
		byte buf[] = new byte[1024];
		int len = 0;
		while((len=is.read(buf))!=-1) {
			os.write(buf,0,len);
			os.flush();
		}
		//关闭流
		os.close();
		is.close();
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值