java批量修改文件後綴

忽然須要改一堆文件的後綴名,因此想編程解決,話很少說直接上代碼

java

import java.io.File;
import java.util.Scanner;

public class FileEdit {

    public static void renameFiles(String path, String oldExt, String newExt) {
        File file = new File(path);
        if (!file.exists()) {
            System.err.println("文件路徑不存在!");
            return;
        }
        File[] files = file.listFiles();
        if (files.length <= 0) {
            System.err.println("當前路徑文件不存在!");
            return;
        }
        for (File f : files) {
            if (f.isDirectory()) {
                renameFiles(f.getPath(), oldExt, newExt);
            } else {
                String name = f.getName();
                if (name.endsWith("." + oldExt)) {
                    name = name.substring(0, name.lastIndexOf(".") + 1);
                    name += newExt;
                    f.renameTo(new File(f.getParent() + "\\" + name));
                }
            }
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("請輸入要修改文件後綴名的文件夾:");
        String path = sc.nextLine();
        System.out.println("請輸入修改前的後綴名:");
        String oldExt = sc.nextLine();
        System.out.println("請輸入修改後的後綴名:");
        String newExt = sc.nextLine();

        renameFiles(path, oldExt, newExt);
        System.out.println("操做完成");
    }
}

其餘方法

  在網上查了下,發現還有cmd命令能夠解決,好比將txt後置改成7z,那麼在你須要修改的目錄運行cmd而後輸入命令ren *.txt *.rar,就能夠將全部txt結尾的文件進行修改;此外能夠將本命令保存爲bat腳本文件,雙擊進行運行。java

相關文章
相關標籤/搜索