将大量图片分组,分别存放不同的文件夹里

package md5;
import java.io.*;

/**
 * @date 2021/02/23
 */
public class Test{
    public static void main(String[] args) {
        File file = new File("E:\\手机照片\\2022-10-10手机照片");
        // 获得图片名列表
        String[] names = file.list();
        // 获得图片列表
        File[] files = file.listFiles();
        assert names != null;
        assert files != null;
        // 需要创建的文件夹数量,每个文件夹放500张图片
        int dirCount = names.length % 500 == 0 ? names.length / 500 : names.length / 500 + 1;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        for(int i = 0;i < dirCount;i++) {
            File tempFile = new File("E:\\手机照片\\2022-10-10手机照片\\图片分组" + (i + 1));
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            FileInputStream fis = null;
            FileOutputStream fos = null;
            System.out.println("正在操作壁纸分组" + (i + 1));
            for(int j = i * 500 ; j < i * 500 + 500 && j < files.length;j++){
                System.out.println("正在操作:" + names[j]);
                try {
                    fis = new FileInputStream(files[j]);
                    fos = new FileOutputStream("E:\\手机照片\\2022-10-10手机照片\\图片分组" + (i + 1)
                            +"\\" + names[j]);
                    bis = new BufferedInputStream(fis);
                    bos = new BufferedOutputStream(fos);
                    byte[] buffer = new byte[1024];
                    int len;
                    while((len = bis.read(buffer)) != -1){
                        bos.write(buffer,0,len);
                        bos.flush();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if(bis != null){
                        try {
                            // 外层流关闭内层流自动关闭,所有不需要fis.close();
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if(bos != null){
                        try {
                            // 外层流关闭内层流自动关闭,所有不需要fos.close();
                            bos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            System.out.println("操作图片分组" + (i + 1) + "成功");
        }

    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值