运用InputStream和OutputStream写个简单的拷贝文件

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;

/** 拷贝文件
 *	1、建立联系 File 对象   源头  目的地
 *	2、选择流    既然是文件的拷贝  那肯定包含了 读取跟写入  所以
 *		1)文件输入流   InputStream FileInputStream 
 *		2)文件输出流  OutputStream FileOutputStream 
 *	3、操作:拷贝  -->一边读取 一边写入  就可以完成拷贝了 
 *		byte flush[] = new byte[1024];
 *		int len = 0;
 *		while(-1=(len=输入流.read(flush))){
 *			输出流.write(flush,0,len);
 *		}
 *		输出流.flush;
 *	4、释放资源:关闭两个流
 */
public class Demo01 {
	public static void main(String[] args){
		String str = new String("e:/work/a.txt");
		String str1 = new String("e:/work/asdfg.txt");
		try {
			copyFile(str, str1);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println("文件未找到!");
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("文件拷贝失败!没事找找bug再来!!!");
		}
		
	}
	public static void copyFile(String srcPath,String datePath) throws FileNotFoundException,IOException{
		//源文件  必须是文件不能是文件夹  输入流是读取不了文件夹的  
		File src = new File(srcPath);
		//目的地  文件可以不存在  
		File date = new File(datePath);
		//打开流
		InputStream it = new FileInputStream(src);
		OutputStream os = new FileOutputStream(date);
		//文件拷贝    
		byte flush[]  = new byte[1024];
		int len = 0;
		while(0<=(len=it.read(flush))){
			os.write(flush, 0, len);
		}
		//关闭流的注意 先打开的后关
		os.close();
		it.close();
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值