JAVA遍历文件夹(多层)下的所有文件,批量修改文件名

JAVA遍历文件夹(多层)下的所有文件,批量修改文件名,很简单的小例子,但有时候却是很实用:

package com.yt;
import java.io.*;
import java.util.ArrayList;

public class Cfile {
	
	private static ArrayList filelist = new ArrayList(); 
    
    public static void main(String[] args) {
        long a = System.currentTimeMillis();
        refreshFileList("/Users/apple/Desktop/images");
        System.out.println(System.currentTimeMillis() - a);
    }
    
    public static void refreshFileList(String strPath) { 
        File dir = new File(strPath); 
        File[] files = dir.listFiles();
        if (files == null) 
            return; 
        for (int i = 0; i < files.length; i++) { 
            if (files[i].isDirectory()) { 
                refreshFileList(files[i].getAbsolutePath()); 
            } else { 
                String fileName = files[i].getName();
                String filePath = files[i].getPath();
               
                System.out.println("fileName-------"+fileName);
                System.out.println("filePath-------"+filePath);
                
                filelist.add(files[i].getAbsolutePath());  
                
                try {
					copyFile(files[i], new File(filePath.replaceAll(fileName, "CUPD_"+fileName)));
				} catch (IOException e) {
					e.printStackTrace();
				}
            } 
        } 
    }
    
    // 复制文件
    public static void copyFile(File sourceFile, File targetFile) throws IOException {
        BufferedInputStream inBuff = null;
        BufferedOutputStream outBuff = null;
        try {
            // 新建文件输入流并对它进行缓冲
            inBuff = new BufferedInputStream(new FileInputStream(sourceFile));
            // 新建文件输出流并对它进行缓冲
            outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));
            // 缓冲数组
            byte[] b = new byte[1024 * 5];
            int len;
            while ((len = inBuff.read(b)) != -1) {
                outBuff.write(b, 0, len);
            }
            // 刷新此缓冲的输出流
            outBuff.flush();
        } finally {
            // 关闭流
            if (inBuff != null)
                inBuff.close();
            if (outBuff != null)
                outBuff.close();
        }
    }
    
}


你可能感兴趣的