Home     RSSRSS

Java Utility – Rename Files in Folder

November 1, 2019 by kiranbadi1991 | Filed under Development, Others.
import java.io.File;
import java.io.IOException;

public class FileRename {

	public static void main(String args[]) throws IOException {		
		String DIR_PATH = "MyDirectoryPath";
		String stringToReplace = "MyStringtoReplaceInFileName";
		getFileNames(DIR_PATH, stringToReplace);
	}

	public static void getFileNames(String Path, String stringToReplace)
			throws IOException {
		File folder = new File(Path);
		File[] listOfFiles = folder.listFiles();
		System.out.println("Total Files :" + listOfFiles.length);
		for (int i = 0; i < listOfFiles.length; i++) {
			if (listOfFiles[i].isFile()) {
				System.out.println("Original File name is : " + listOfFiles[i].getName());
			} else if (listOfFiles[i].isDirectory()) {
				System.out.println("Directory " + listOfFiles[i].getName());
			}
			renameFile(listOfFiles[i], stringToReplace);

		}
	}

	public static void renameFile(File fileItem, String stringToReplace)
			throws IOException {
		String fileName = fileItem.getName();
		if (fileName.contains(stringToReplace)) {
			String newName = fileName.replace(stringToReplace, "");
			File fileWithNewName = new File(fileItem.getParent(), newName);
			if (fileWithNewName.exists()) {
				System.out.println("File cannot be renamed as 2 files exist with same name so deleting 1 file " + fileWithNewName.getName());
				fileWithNewName.delete();
			}
			boolean success = fileItem.renameTo(fileWithNewName);
			System.out.println("New FileName is " + fileWithNewName.getName());
			if (!success) {
				System.out.println("File cannot be renamed " + fileWithNewName.getName());
			}
		}

	}

}

← Previous

Tags:

Comments are disabled