文件复制实现

package study;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

public class FileCopy {
	public static void main(String[] args) throws UnsupportedEncodingException{
		try {
			copyFile("C:\\Users\\Wll\\Desktop\\yy.txt", "C:\\Users\\Wll\\Desktop\\copy.txt");
			System.out.println("复制成功!");
		} catch (IOException e) {
			System.out.println("复制失败!");
			System.out.println(e.getMessage());
		}
	}
	
	/**
	 * 将 source 路径对应的文件复制到 dest 路径对应的文件
	 * @param source 源文件
	 * @param dest 目标文件
	 * @throws IOException
	 */
	public static void copyFile(String source, String dest) throws IOException {
		InputStream in = new FileInputStream(source);
		OutputStream out = new FileOutputStream(dest);
		
		byte[] buff = new byte[1024]; // 对每次读入的数据进行缓存
		int len = 0; // 每次读取数据的长度
		
		// 边读取边复制
		while ((len = in.read(buff)) != -1) { 
			// read() 从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。在某些输入可用之前,此方法将阻塞。
			out.write(buff, 0, len);
		}
		
		in.close();
		out.close();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值