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

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();
		
	}	
}

猜你喜欢

转载自blog.csdn.net/qq_30007589/article/details/81082921