使用字节流实现文件复制

版权声明:原创内容是本人学习总结,仅限学习使用,禁止用于其他用途。如有错误和不足,欢迎评论指正补充。 https://blog.csdn.net/qian_qian_123/article/details/85243225
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();
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qian_qian_123/article/details/85243225