使用字节流实现文件复制

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;

/**
 * 使用字节流复制文件,文件可以是音频和视频,文本文档
 * 可以根据需要调整缓冲数组b的长度
 * 
 * @author zhangwendi
 *
 */
public class FileCopy {

	public static void main(String[] args) {
		File source = new File("D:/1.jpg");
		File target = new File("D:/1111.jpg");
		copyFileByStream(source, target);
	}

	public static void copyFileByStream(File sourceFile, File targetFile) {
		// 判断源文件是否存在,如果不存在,就退出程序
		if (!sourceFile.exists()) {
			System.out.println("源文件不存在,程序退出");
			System.exit(0);
		}
		// target.getParentFile()表示用来获取目标对象的父目录对象
		// 如果目标文件路径不存在,就创建
		if (!targetFile.getParentFile().exists()) {
			targetFile.getParentFile().mkdirs();
		}
		InputStream is = null;
		OutputStream os = null;
		try {
			// 准备输入流
			is = new FileInputStream(sourceFile);
			// 准备输出流
			os = new FileOutputStream(targetFile);
			// 准备一个数组,作为缓冲,用来存放读写的数据
			byte[] b = new byte[1024];
			int len = -1;
			// read(b)实现读取操作,数据存入b数组,返回读取长度给len,当所有内容都读取完毕,len=-1
			while ((len = is.read(b)) != -1) {
				// 实现写的操作
				os.write(b, 0, len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
				if (os != null) {
					os.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

 

  • 4
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值