Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

เปลี่ยนชื่อไฟล์หลายไฟล์ใน Java: Rename Multiple Files

การเปลี่ยนชื่อไฟล์หลายไฟล์ (Batch Rename)

ใช้ java.io.File และ listFiles() ดึงไฟล์ทั้งหมดในโฟลเดอร์ แล้ววนลูป rename

ตัวอย่างโค้ด

import java.io.File; 
import java.io.IOException; 

public class Demo { 
    public static void main(String[] argv) throws IOException { 
        String folderPath = "path/to/folder/with/files"; 
        File folder = new File(folderPath); 
        
        File[] files = folder.listFiles(); 
        if (files == null) { 
            System.out.println("โฟลเดอร์ไม่มีอยู่ หรือไม่ใช่ directory"); 
            return; 
        } 
        
        for (File file : files) { 
            if (file.isFile()) { 
                String oldName = file.getName(); 
                
                // ตัวอย่าง: เปลี่ยนนามสกุลเป็น .pdf และตัดคำแรกออก
                String[] parts = oldName.split("\\s+"); // split by whitespace
                String newName = (parts.length > 1) ? parts[1] : oldName; 
                newName += ".pdf"; 
                
                File newFile = new File(folder, newName); 
                
                System.out.println("Renaming: " + oldName + " -> " + newName); 
                
                boolean success = file.renameTo(newFile); 
                if (!success) { 
                    System.err.println("ล้มเหลว: " + oldName); 
                } 
            } 
        } 
    } 
}

คำอธิบาย

  1. folder.listFiles() คืน array ของ File objects ในโฟลเดอร์
  2. ตรวจสอบ file.isFile() (ข้าม subdirectories)
  3. split("\\s+") แยกชื่อไฟล์ด้วย whitespace (regex)
  4. สร้างชื่อใหม่จากส่วนที่ 2 (index 1) + ".pdf"
  5. renameTo() คืน true/false แสดงผลสำเร็จ

ข้อควรระวังสำคัญ

  • renameTo() behavior แตกต่างตาม OS: Windows ไม่ให้ rename ข้าม drive, Unix อาจได้
  • ไม่ overwrite ไฟล์เดิม หาก newFile มีอยู่แล้ว → คืน false
  • Atomic ไม่ได้รับประกัน บนบางระบบ
  • Java 7+ ควรใช้ NIO.2 (Files.move) - ใช้ได้ดีกว่า รองรับ REPLACE_EXISTING, ATOMIC_MOVE

เวอร์จันปรับปรุงด้วย NIO.2 (แนะนำ)

import java.io.IOException; 
import java.nio.file.*; 
import java.nio.file.attribute.BasicFileAttributes; 

public class BatchRename { 
    public static void main(String[] args) throws IOException { 
        Path folder = Paths.get("path/to/folder"); 
        
        Files.walkFileTree(folder, new SimpleFileVisitor() { 
            @Override 
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { 
                String oldName = file.getFileName().toString(); 
                String[] parts = oldName.split("\\s+"); 
                String newName = (parts.length > 1 ? parts[1] : oldName) + ".pdf"; 
                
                Path target = file.resolveSibling(newName); 
                
                try { 
                    Files.move(file, target, StandardCopyOption.REPLACE_EXISTING); 
                    System.out.println("Renamed: " + oldName + " -> " + newName); 
                } catch (IOException e) { 
                    System.err.println("Failed: " + oldName + " - " + e.getMessage()); 
                } 
                return FileVisitResult.CONTINUE; 
            } 
        }); 
    } 
}

รูปแบบการ rename ที่พบบ่อย

// 1. เพิ่ม prefix
newName = "prefix_" + oldName;

// 2. เปลี่ยน extension
newName = oldName.replaceFirst("\\.[^.]+$", "") + ".pdf";

// 3. เพิ่ม timestamp
newName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")) + "_" + oldName;

// 4. Zero-padded numbering
int count = 1;
for (File f : files) {
    String newName = String.format("img_%03d.jpg", count++);
    // ...
}