Filehandling - Get Files with FilenameFilter and rename them
Can please someone tell me how to make this code more readable with syntax highlighting? I figured something out, but its not Java-Highlighting yet.
Basicly this class can get Files from a directory and rename them. So this is just a convenience class.
import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; /** * Basicly this class can get Files from a directory and rename them.
* So this is just a convenience class
* * @author javaknowledgecafe.tumblr.com */ public final class FileHandler { private FileHandler() { // no instances allowed } /** * @param dir * @param filenameFilter * {@link FilenameFilter}, if null all files are taken from the * {@code dir} * @return files, which match the criterias defined in * {@code filenameFilter} */ public static List<File> getFilesFromDirectory(final File dir, final FilenameFilter filenameFilter) { File[] allFilesWithOrWithFilePattern = null; if (filenameFilter == null) { allFilesWithOrWithFilePattern = dir.listFiles(); } else { allFilesWithOrWithFilePattern = dir.listFiles(filenameFilter); } return Arrays.asList(allFilesWithOrWithFilePattern); } /** * @param filesToRename * Map with File as key and new Filename as value * @return Files, which couldn't be renamed * @throws Exception */ public static List<String> renameFiles( final Map<File, String> filesToRenameWithNewNames) { final List<String> notSuccessfulRename = new ArrayList<String>(); for (final Map.Entry<File, String> entry : filesToRenameWithNewNames .entrySet()) { final File fileToRename = entry.getKey(); final String newFilename = entry.getValue(); final boolean success = renameFileToFileSystem(fileToRename, newFilename); if (!success) { notSuccessfulRename.add(fileToRename.getName()); } } return notSuccessfulRename; } /** * * @param fileToRename * @param newFilenameWithoutFileType * @return */ private static boolean renameFileToFileSystem(final File fileToRename, final String newFilenameWithoutFileType) { // end of the new path (without the name) final int endOfPath = fileToRename.getAbsolutePath().lastIndexOf("\\"); // complete new filepath with filename final String pathAndNewFileName = fileToRename.getAbsolutePath() .substring(0, endOfPath + 1) + newFilenameWithoutFileType.trim(); final File fileNew = new File(pathAndNewFileName); final boolean success = fileToRename.renameTo(fileNew); return success; } }












