批量修改文件名的例子

package jrx.anytask.controller;

import com.google.common.collect.Lists;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Pattern;

public class GenTestFile {

    static String sourcedir = "D:\\download\\sourcefiles";//文件夹路径,所有文件的根目录,记得修改为你电脑上的文件所在路径
    static String targetdir = "D:\\download\\targetfiles";//目标文件夹根目录
    public static void main(String[] args) throws IOException {
        recursiveTraversalFolder(sourcedir,targetdir);//递归遍历此路径下所有文件夹
    }
    /**
     * 递归遍历文件夹获取文件
     */
    public static void recursiveTraversalFolder(String sourcedir,String targetdir) {
        File folder = new File(sourcedir);
        if (folder.exists()) {
            File[] fileArr = folder.listFiles();
            if (null == fileArr || fileArr.length == 0) {
                System.out.println("文件夹是空的!");
                return;
            } else {
                String newName = null;
                File newDir = null;
                for (String ss: idNoList()) {
                    for (File file : fileArr) {
                        newName = file.getName().replace("************",ss);
                        newDir = new File(targetdir+ File.separator+ newName);//文件所在文件夹路径+新文件名
                        try {
                            copy(file,newDir);
                        } catch (Exception e) {
                            e.printStackTrace();
                            System.out.println("id" + ss + "复制失败!");
                            System.out.println("失败文件" + newDir.getName());
                        }
                    }
                    System.out.println("id:【" + ss + "】复制完成");
                }

            }
        } else {
            System.out.println("文件不存在!");
        }
    }
    private static void copy(File source, File target) throws Exception {
        try(FileInputStream in = new FileInputStream(source);
            FileOutputStream out = new FileOutputStream(target)){
            byte[] buff = new byte[512];
            int n = 0;
            System.out.println("复制文件:" + "\n" + "源路径:" + source.getAbsolutePath() + "\n" + "目标路径:"
                    + target.getAbsolutePath());
            while ((n = in.read(buff)) != -1) {
                out.write(buff, 0, n);
            }
            System.out.println("复制完成");
        }

    }

    public static ArrayList<String> idNoList() {
        ArrayList<String> objects = Lists.newArrayList();
        objects.add("***************");
        return objects;
    }
}
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值