使用文件输入流和输出流实现文件拷贝 (代码)

文件拷贝

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;

/**
* @author 黑羽-孤高之银风
* @version 创建时间:2019年6月12日 上午10:31:51
* 使用文件输入流和输出流实现文件拷贝
*/
public class CopyFile {
	public static void main(String[] args){
		copyFile("C:/Users/XX/Desktop/start.txt","C:/Users/XX/Desktop/end.txt");
	}	
	public static void copyFile(File src,File dest){
		//1.选择流
		InputStream  is=null;
		OutputStream os=null;
		try {
			is=new FileInputStream(src);
			os=new FileOutputStream(dest);
			//2.准备卡车
			 byte[] car=new byte[1024];
			 //3.读入写出
			 int len=-1;  //读入到小卡车中数据的个数
			 while((len=is.read(car))!=-1){
				 os.write(car,0,len);
			 }
			//4.刷出
			os.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			//5.关闭   先打开的后关闭
			try {
				//多行添加try..catch=>alt+shift+z
				if(os!=null){
					os.close();
				}
				if(is!=null){
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	//封装好的复制文件方法
		public static void copyFile(String srcPath,String destPath){ //开始路径 目标路径
		//1.创建源
		File src = new File(srcPath);
		File dest = new File(destPath);
		//2.选择流
		InputStream is = null;
		OutputStream os = null;
		try {
			is = new FileInputStream(src);
			os = new FileOutputStream(dest);
			//3.操作★★★
			byte[] flush = new byte[1024];//缓冲容器
			int len = -1;
			if ((len=is.read(flush))!=-1) {
				os.write(flush, 0, len);
				
			}
			os.flush();//刷出
		} catch (Exception e) {

		}finally {
			//4.关闭流
			if (os!=null) {
				try {
					os.close();
				} catch (IOException e) {
					
					e.printStackTrace();
				}
			}
			if (is!=null) {
				try {
					is.close();
				} catch (IOException e) {
					
					e.printStackTrace();
				}
			}
			
		}
	}
}
  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值