package com.basic.security.utils; import java.io.File; public class RenameFiles { static String dirName = "F:\\ttorial.com_sorted\\linux\\[Ttorial.Com] Advanced Linux_ The Linux Kernel"; static String[] videoExtensions = { ".flv", ".mp4", ".mov", ".wmv", ".flv" }; public static void main(String[] args) { if (!dirName.endsWith("\\")) { dirName += "\\"; } File file = new File(dirName); if (!file.exists()) { file.mkdir(); } listSubDir(); } private static void listSubDir() { File dir = new File(dirName); File[] subDirs = dir.listFiles(); for (File subDir : subDirs) { // System1.out.println(subDir.getAbsolutePath()); if (subDir.isFile()) { String prefix = getPrefix(subDir); if (isVideoFile(subDir)) { rename(prefix, subDir); } } if (subDir.isDirectory()) { listFileInSubDir(subDir); } } } private static void listFileInSubDir(File subDir) { File files[] = subDir.listFiles(); String prefix = getPrefix(subDir); if (files == null) { return; } for (File file : files) { if (isVideoFile(file)) { rename(prefix, file); } } } private static String getPrefix(File subDir) { String dirName = subDir.getName(); if (dirName.length() > 3) { dirName = dirName.substring(0, 3); } return dirName = dirName.replaceAll("\\D+", ""); } private static void rename(String prefix, File file) { String prefixPattern = prefix + "_"; if (file.getName().contains("\\" + prefixPattern)) { return; } // prefixPattern = ""; String newFileName = dirName + prefixPattern + file.getName(); System1.out.println(file.getAbsolutePath() + "---" + newFileName); file.renameTo(new File(newFileName)); } private static boolean isVideoFile(File file) { if (file.isDirectory()) { return false; } String fileName = file.getName(); for (String extension : videoExtensions) { if (fileName.endsWith(extension)) { return true; } } return false; } }