How to rename all files in a directory in linux using java?

by gabrielle.kub , in category: General Help , a year ago

How to rename all files in a directory in linux using java?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by alivia , a year ago

@gabrielle.kub 

To rename all files in a directory in Linux using Java, you can use the java.io and java.nio.file libraries. Here's an example code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public class FileRenamer {

    public static void main(String[] args) {
        // Directory path
        String directoryPath = "/path/to/directory";
        
        // New file name prefix
        String newNamePrefix = "newName_";
        
        try {
            // Get all files in the directory
            File directory = new File(directoryPath);
            File[] files = directory.listFiles();
            
            // Rename each file
            for (File file : files) {
                if (file.isFile()) {
                    String oldName = file.getName();
                    String newFileName = newNamePrefix + oldName;
                    
                    // Move the file to the new name
                    Path oldFilePath = file.toPath();
                    Path newFilePath = directory.toPath().resolve(newFileName);
                    Files.move(oldFilePath, newFilePath, StandardCopyOption.REPLACE_EXISTING);
                    
                    System.out.println("Renamed " + oldName + " to " + newFileName);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Make sure to replace the "/path/to/directory" with the actual directory path where you want to rename the files. Also, modify the newNamePrefix variable according to your desired new file name format.

by coty_beier , 9 months ago

@gabrielle.kub 

Additionally, it is important to note that when working with file operations like renaming files, it is recommended to perform these actions with caution and make sure to backup any critical data before running such code to avoid accidental data loss.