InputStream和OutputStream对文件夹和文件的复制

Java IO流对多层文件夹的复制问题

package com.Test.A;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/*
 * InputStream和OutputStream的复制文件和文件夹问题
 */
public class StreamTest {
	public static void main(String[] args) {
		File f1 = new File("D:\\ECE");
		File f2 = new File("D:\\haha");
		copyAllDrictory(f1, f2);
	}

	public static void copyAllDrictory(File start, File end) {
		// 声明输入输出流
		BufferedInputStream bufferedInputStream = null;
		BufferedOutputStream bufferedOutputStream = null;
		// 对IO流异常进行处理
		try {
			// 判断读取是否是文件夹
			if (start.exists()) {
				if (start.isDirectory()) {
					// 遍历文件夹
					for (File i : start.listFiles()) {
						if (i.isDirectory()) {
							System.out.println(i);
							File f = new File(end, i.getName());
							f.mkdirs();
							System.out.println(f);

							copyAllDrictory(i, f);
						} else {
							bufferedInputStream = new BufferedInputStream(new FileInputStream(i));
							String endname = i.getName();
							bufferedOutputStream = new BufferedOutputStream(
									new FileOutputStream(new File(end, endname)));
							int len = 0;
							byte[] bytes = new byte[2048];
							while ((len = bufferedInputStream.read(bytes)) != -1) {
								bufferedOutputStream.write(bytes, 0, len);
							}
						}

					}
				} else {
					// 不是文件夹
					bufferedInputStream = new BufferedInputStream(new FileInputStream(start));
					bufferedOutputStream = new BufferedOutputStream(
							new FileOutputStream(new File(end, start.getName())));
					int len = 0;
					byte[] bytes = new byte[2048];
					while ((len = bufferedInputStream.read(bytes)) != -1) {
						bufferedOutputStream.write(bytes, 0, len);
					}
				}
			} else {
				System.out.println("文件夹路径不正确");
			}
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("文件复制失败,请重试");
		} finally {
			// 关流
			try {
				if (bufferedOutputStream != null)
					bufferedOutputStream.close();
			} catch (IOException e) {
				throw new RuntimeException("文件复制失败,请重试");
			} finally {
				try {
					if (bufferedInputStream != null)
						bufferedInputStream.close();
				} catch (IOException e) {
					throw new RuntimeException("文件复制失败,请重试");
				}
			}

		}
	}
}


若是有工具包工具包优先
commons-io工具类挺好 org.apache.commons.io.FileUtils

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值