IO流实现批量文件复制转移

IO流实现批量文件复制转移

package com.armin.test;

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

public class IOTest {

	public static void main(String[] args) throws IOException, InterruptedException {
		
		String src = "D:\\BigData";
		String target = "D:\\test\\test2";
		long begin = System.currentTimeMillis();
		fileCopyPaste(src, target);
		long end = System.currentTimeMillis();
		System.out.println((end-begin)/1000);// 211s char[]
		
	}
	/**
	 * 批量文件的复制转移(字节流)
	 * @param src
	 * @param target
	 * @throws IOException 
	 */
	public static void fileCopyPaste(String src, String target) throws IOException{
		File srcfile = null; 
		File targetfile = null; 
		FileInputStream in = null;
		FileOutputStream out = null;
		// 文件目录共享区域
		String common = null;
		// 判断文件对象是否已经被创建,没有则执行
		if (srcfile==null && targetfile==null) {
			srcfile = new File(src);
			targetfile = new File(target);
		}
		// 如果 src 不存在,函数结束
		if (!srcfile.exists()) {
			System.err.println("Source file not found !");
		} else {
			// 如果目标文件夹不存在,则创建
			if (!targetfile.exists()) {
				targetfile.mkdirs();
			} 
			// 如果源文件是目录,则遍历目录,单独操作
			if (srcfile.isDirectory()) {
				File[] listFiles = srcfile.listFiles();
				for (File file : listFiles) {
					if (file.isDirectory()) {
						// 接收目录(否则,从遍历的第二个文件夹开始,永远都会在下一层目录)
						common = target + File.separator + file.getName();
						// 递归,拷贝目录
						fileCopyPaste(file.getAbsolutePath(), common);
						// 控制台打印文件进度
						System.out.println(file.getAbsolutePath()+"____"+common);
					} else {
						// 拷贝文件名
						new File(targetfile, file.getName()).createNewFile();
						/**
						 * 文件传输区域
						 */
						in = new FileInputStream(file.getAbsolutePath());
						out = new FileOutputStream(targetfile + File.separator + file.getName());
						byte[] data = new byte[1024];
						// byte数组返回的长度
						int len;
						while ((len=in.read(data)) != -1) {
							out.write(data, 0, len);
						}
						out.close();
						in.close();
					} 
				}
			} else {
				// src 为文件 则 拷贝该文件
				new File(targetfile, srcfile.getName()).createNewFile();
				/**
				 * 文件传输区域
				 */
				in = new FileInputStream(srcfile.getAbsolutePath());
				out = new FileOutputStream(targetfile + File.separator + srcfile.getName());
				byte[] data = new byte[1024];
				int len;
				while ((len=in.read(data)) != -1) {
					out.write(data, 0, len);
				}
				out.close();
				in.close();
			}
		}
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值