Ablia
Ablia

Reputation: 327

RenameTo seems to fail randomly

There is a lot of post about RenameTo, but infortunately none of it seems to be my problem or answer it :'(

My problem is: i give a file to my prog, then it shoud encrypt it, calculate the hash of the encrypted file, and rename this encrypted file with this hash. To do it, i first create the encrypted file with the name "tmp", then i calculate his name (with the call "myfile.setFileID()" in the code below) and then i use RenameTo to rename it.

The encryption work well, the hashfunction too (no doubt here, i used both for a while before trying to implement that). In fact, everything works well....except sometimes RenameTo fail. And i don't know why.

Here's the part of code where i use RenameTo:

            //encrypt file:
            File tmpEncryptedFile = Crypt.encrypt(originalFile, aesKey);

            //set File ID and rename file: 
            myfile.setFileID(tmpEncryptedFile);
            File encryptedFile = new File(myfile.getFileID());
            if(!tmpEncryptedFile.renameTo(encryptedFile)) {
                System.err.println("unable to rename file. Upload failed. Please try again.");
            }

Sometimes it works well, sometimes i got the "unable to rename file". Each time, the tmp file is correctly created, so it seems that really comes from renameTo. Plus, i've runned a lot of tests now, and it can fail or work with the same file input (oh, except that the encrypted file will not be the same even for the same input file, since the key is random...so yes, the input for RenameTo is not the same, but i mean it's not a "file not found" problem or a problem from another part of my program).

For example, i can run the program times, each times giving it the same file, and the two first time fails, the third one works well. Or i can run it 10 times, the 9 first times works well and the last one fail. Since the fails appears to be random, i can't understand what doesn't work here.

I've read that i could maybe use Files.move() instead, but it seems more "logical" to me to use RenameTo() and i would like to understand what is wrong here. Plus, Files.move() use a path, and i just want it to be done in my project directory so the file name is enough for me.

Upvotes: 0

Views: 111

Answers (1)

piet.t
piet.t

Reputation: 11921

Assuming that your new filename is a Base64-encoded hash-value I'm pretty sure the rename will fail in those cases where the new filename contains a /. When trying to rename the file to "abc/def" renameTo will interpret the abc-part as a directory. Since this directory does not exist renameTo will fail (it does not implicitly create it).

Upvotes: 1

Related Questions