Last active
November 30, 2024 17:49
-
-
Save albertus82/2c4e247f99a886e76b5051f015895dcb to your computer and use it in GitHub Desktop.
Batch renamer (preserves extensions)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.io.FileNotFoundException; | |
import java.io.IOException; | |
import java.util.Arrays; | |
import java.util.Set; | |
import java.util.TreeSet; | |
public class Renamer { | |
public static void main(final String[] args) throws FileNotFoundException, IOException { | |
if (args.length != 2) { | |
throw new IllegalArgumentException(); | |
} | |
final String srcDirName = args[0].trim(); | |
final File srcDir = new File(srcDirName); | |
if (!srcDir.isDirectory()) { | |
throw new FileNotFoundException(srcDir.getCanonicalPath()); | |
} | |
final String dstDirName = args[1].trim(); | |
final File dstDir = new File(dstDirName); | |
if (!dstDir.isDirectory()) { | |
throw new FileNotFoundException(dstDir.getCanonicalPath()); | |
} | |
final Set<String> srcFileNames = new TreeSet<>(); | |
Arrays.asList(srcDir.list()).stream().forEach(srcFileNames::add); | |
final Set<String> dstFileNames = new TreeSet<>(); | |
Arrays.asList(dstDir.list()).stream().forEach(dstFileNames::add); | |
if (srcFileNames.size() != dstFileNames.size()) { | |
throw new IllegalStateException(); | |
} | |
final String[] srcFileNamesArray = srcFileNames.toArray(new String[] {}); | |
final String[] dstFileNamesArray = dstFileNames.toArray(new String[] {}); | |
for (int i = 0; i < srcFileNames.size(); i++) { | |
final String dstFileName = dstFileNamesArray[i]; | |
final String srcFileName = srcFileNamesArray[i]; | |
final File oldNamedFile = new File(dstDir + File.separator + dstFileName); | |
final File newNamedFile = new File(dstDir + File.separator + srcFileName.replace(srcFileName.substring(srcFileName.lastIndexOf('.')), dstFileName.substring(dstFileName.lastIndexOf('.')))); | |
if (!oldNamedFile.toString().equals(newNamedFile.toString())) { // case-sensitive | |
System.out.printf("%s -> %s%s", oldNamedFile.toString(), newNamedFile.getName(), System.lineSeparator()); | |
if (!oldNamedFile.renameTo(newNamedFile)) { | |
throw new RuntimeException(); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment