3

I have this code in Java. The randomName() function returns a string with (unsurprisingly) a 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 to logcat the randomName() function does all the strings, but upon the end of the loop handle appears to have a file name of the value of the first randomName() call.

Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • 2
    I'd say it should be the value of the last `randomName()` call; – A--C Jan 24 '13 at 19:41
  • I believe it's a problem with handler, as the first renameTo returns true but the rest are false – user2008804 Jan 24 '13 at 19:49
  • Log the values of `lastName` in the for loop. `renameTo()` shouldn't affect the value of `lastName`. – A--C Jan 24 '13 at 19:52
  • That should make the question easier to answer :) – Jason Sperske Jan 24 '13 at 19:54
  • A--C: I logged and that part is working fine (all lastName's are unique) I then logged values of .renameTo and found that the first is true, but the rest return false – user2008804 Jan 24 '13 at 19:57
  • 1
    @user2008804 If you solved it, you can make an answer to your question so other people facing the same issue can see what worked. – A--C Jan 24 '13 at 20:03

2 Answers2

0

The reason this didn't work as expected is because once the file was renamed the first time, handle no longer referred to the file. That is why the subsequent rename operations failed. File represents a path name, not an actual object on disk.

Phil
  • 2,238
  • 2
  • 23
  • 34
0

This is my solution:

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);
            }

        }