File rename error in for loop

I have this code in Java. The randomName () function returns a string with a (unsurprisingly) random string.

File handle = new File(file);
String parent = handle.getParent();
String lastName = "";
for (int i = 0; i < 14; i++)
{
    lastName = parent + File.separator + randomName();
    handle.renameTo(new File(lastName));
}
return lastName;

      

I have the appropriate permissions, and when I log in logcat, the randomName () function does all the lines, but at the end of the loop handle

, the filename appears for the first randomName () value call.

+3


source to share


2 answers


This is my decision:



File handle = null;
        String parent = "";
        String lastName = "";

        for (int i = 0; i < 14; i++)
        {
            if (i == 0)
            {
                handle = new File(file);
                parent = handle.getParent();
            }
            else
            {
                lastName = parent + File.separator + randomName();
                handle.renameTo(new File(lastName));
                handle = new File(lastName);
            }

        }

      

0


source


The reason this doesn't work as expected is because once the file has been renamed the first time, it handle

no longer references the file. This is why subsequent rename operations failed. File

is a pathname, not an actual object on disk.



0


source







All Articles