Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The last character in a folder name can't be replaced

I use .replace() instructions in order to clean up folder names. This worked fine for these characters so far: {".", " ", "(", "["} but as soon as I got to the closing brackets, I receive an error. When I look at the folder which threw this error it always has a closing bracket at the end. Upon manually removing the closing bracket and executing the code again, an error occurs at the next folder with a trailing bracket.

In every case the characters are being replaced with a single space.

public void cleanFormat() {
    for (int i = 0; i < directories.size(); i++) {
        File currentDirectory = directories.get(i);
        for (File currentFile : currentDirectory.listFiles()) {
            String formattedName = currentFile.getName();
            formattedName = formattedName.replace(".", " ");
            formattedName = formattedName.replace("(", " ");
            formattedName = formattedName.replace(")", " "); // error here
            formattedName = formattedName.replace("[", " ");
            formattedName = formattedName.replace("]", " "); // and here
            formattedName = formattedName.replace("  ", " ");
            Path source = currentFile.toPath();
            try {
                Files.move(source, source.resolveSibling(formattedName));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    JOptionPane.showMessageDialog(null, "All folders have been formatted");
}

Error being:

Exception in thread "AWT-EventQueue-0" java.nio.file.InvalidPathException: Trailing char < > at index 68: A Good Old Fashioned Orgy 2011 LIMITED 720p BluRay X264-AMIABLE EtHD 
at sun.nio.fs.WindowsPathParser.normalize(Unknown Source)
at sun.nio.fs.WindowsPathParser.parse(Unknown Source)
at sun.nio.fs.WindowsPathParser.parse(Unknown Source)
at sun.nio.fs.WindowsPath.parse(Unknown Source)
at sun.nio.fs.WindowsFileSystem.getPath(Unknown Source)
at sun.nio.fs.AbstractPath.resolveSibling(Unknown Source)
at domain.DirectoryListing.cleanFormat(DirectoryListing.java:86)

Name of folder:

A Good Old Fashioned Orgy 2011 LIMITED 720p BluRay X264-AMIABLE EtHD]
like image 608
Jeroen Vannevel Avatar asked Dec 08 '12 13:12

Jeroen Vannevel


1 Answers

You are getting this exception because you have a space as the last character in your file name and underlying OS (Windows) will not accept a file name with a trailing space character.

This space as a trailing character is most likely result of multiple String#replace calls, make sure you don't replace very last char in the String with space.

like image 188
anubhava Avatar answered Oct 13 '22 00:10

anubhava