Java线程与IO拷贝文件

Java文件操作

IO+线程–>复制文件

public class Test {
    // 测试
    @Test
    public void test() throws IOException {
        turnFile(new File("E:\\学习文件\\shimmer"), new File("E:\\学习文件\\SHIMMER"));
    }

    /**
	 * 文件复制控制方法
	 */
    public void turnFile(File source, File target) throws IOException {
        ExecutorService pool = newFixedThreadPool(5);
        String prefix = target.getPath();
        String suffix;
        if (!source.exists()) return;
        File[] files = source.listFiles();
        if (files == null || files.length == 0) return;
        for (File file : files) {
            suffix = "\\" + file.getName();
            if (file.isFile()) {
                pool.execute(new CopyFile(file, prefix + suffix));
            } else {
                File targetT = new File((prefix + suffix));
                if (targetT.mkdir()) {
                    turnFile(file, targetT);
                }else {
                    System.out.println("创建目标文件失败!");
                }
            }
        }
        
        // 这里的休眠是让主线程等待其他线程操作结束,否则主线程结束后虚拟机关闭,就会出现文件复制不完全
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

/**
 * 文件复制线程
 */
class CopyFile extends Thread {
    File source;
    File target;
    
	/**
	 * 构造器,初始化操作的文件对象信息
	 */
    public CopyFile(File source, String target) {
        if (source.exists() && target != null) {
            this.source = source;
            this.target = new File(target);
        }
    }

    @Override
    public void run() {
        try {
            InputStream is = new FileInputStream(source);
            OutputStream os = new FileOutputStream(target, true);
            
            // 其实用上面的两个低级流完全可以做,但是效率太低,缓冲流会大幅度提高传输速度
            BufferedInputStream bis = new BufferedInputStream(is);
            BufferedOutputStream bos = new BufferedOutputStream(os);
            byte[] b = new byte[1024];
            while (bis.read(b) != -1) {
                bos.write(b);
                bos.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值