简单的多线程复制文件

 Demo.class

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

public class demo {
    private static String sourceRootPath = "D:\\source-photo\\";
    private static String toRootPath = "D:\\compressed-photo\\";
    private static AtomicInteger count = new AtomicInteger(2);
    private static AtomicInteger index = new AtomicInteger(0);
    private static final int workSize = 8;

    public static void main(String[] args) {
        /*try {
            copyFiles(1000);
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        try {
            compressPhotoFiles();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void compressPhotoFiles() throws InterruptedException {
        // TODO 检查路径是否合法
       
        List<File> list = new ArrayList<>(FileUtils.listFiles(new File(sourceRootPath),new String[]{"png","jpg"},true));
        Calendar start = Calendar.getInstance();
        ExecutorService executor = Executors.newFixedThreadPool(workSize);
        for(int i=0;i<=workSize;i++){
            executor.submit(new CompressPhotoRunnable(list,toRootPath,index));
        }
        executor.shutdown();
        while(true){
            if (executor.isTerminated()) {
                double minute = (Calendar.getInstance().getTimeInMillis() - start.getTimeInMillis())/1000/60.0;
                System.out.println("图片压缩完成:"+minute+"分钟");
                break;
            }
            Thread.currentThread().sleep(1000);
        }
    }


    public static void copyFiles(int size) throws ExecutionException, InterruptedException {
        Calendar start = Calendar.getInstance();
        ExecutorService executor = Executors.newFixedThreadPool(workSize);
        ArrayList<Boolean> list = new ArrayList<>();
        for (int i=1;i<=workSize;i++){
            Future<Boolean> isOk = executor.submit(new CopyFileCallable(sourceRootPath,i,count,size));
            list.add((Boolean) isOk.get());
        }
        System.out.println(list.toString());
        executor.shutdown();
        while(true){
            if (executor.isTerminated()) {
                double minute = (Calendar.getInstance().getTimeInMillis() - start.getTimeInMillis())/1000/60.0;
                System.out.println("图片复制完成:"+minute+"分钟");
                break;
            }
            Thread.currentThread().sleep(1000);
        }
    }
}

线程类CopyFileRunnable,创建大量图片用于测试

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;

public class CopyFileCallable implements Callable {
    private String fromPath;
    private Integer index ;
    private AtomicInteger count;
    private static Integer size;

    public CopyFileCallable(String fromPath,Integer index,AtomicInteger count,Integer size){
        this.fromPath = fromPath;
        this.index = index;
        this.count = count;
        this.size = size;

    }

    @Override
    public Boolean call() throws Exception {
        String fromPath = this.fromPath + index + ".jpg";
        int addCount = 0;
        File from = new File(fromPath);
        while(!from.exists()){
            try {
                Thread.currentThread().sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            from = new File(fromPath);
        }

        while((addCount=count.getAndAdd(1))<=size && from.canRead()){
            System.out.println(addCount);

            String toPath = fromPath + addCount + ".jpg";
            File to = new File(toPath);
            try {
                if(!to.exists()){
                    Files.copy(from.toPath(),to.toPath());
                    // System.out.println("图片线程"+i+"-"+(addCount+1)+" 已创建");
                }
            } catch (IOException e) {
                // e.printStackTrace();
                System.out.println("文件"+addCount+".jpg 复制失败:"+e.getMessage());
            }
            to = null;
        }
        return true;
    }
}

压缩图片线程类

import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FileUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class CompressPhotoRunnable implements Runnable{
    private List<File> files;
    private String toPath;
    private AtomicInteger index;

    public CompressPhotoRunnable(List<File> files, String toPath, AtomicInteger index) {
        this.files = files;
        this.toPath = toPath;
        this.index = index;
    }

    @Override
    public void run() {
        int nowIndex = 0;
        File file;
        double scale = 1;
        int min;
        while ((nowIndex=index.getAndAdd(1))<=files.size()){
            System.out.println(nowIndex);
            try {
                file = files.get(nowIndex);
                BufferedImage buff = ImageIO.read(file);
                if((min = Math.min(buff.getHeight(),buff.getWidth()))>500){
                    // 小的边根据比例压缩到500像素
                    scale = Math.round((500.00/min*100))/100.00;
                }
                Thumbnails.of(buff).scale(scale).toFile(toPath+file.getName());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值