简体   繁体   English

在for循环中重命名文件时出错

[英]Error renaming a File in a for loop

I have this code in Java. 我在Java中有这个代码。 The randomName() function returns a string with (unsurprisingly) a random string. randomName()函数返回一个带有(不出所料)随机字符串的字符串。

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. 我有适当的权限,当我登录到logcat时,randomName()函数会执行所有字符串,但是在循环结束时, handle似乎具有第一个randomName()调用值的文件名。

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. 这不能按预期工作的原因是因为一旦第一次重命名文件, handle就不再引用该文件了。 That is why the subsequent rename operations failed. 这就是后续重命名操作失败的原因。 File represents a path name, not an actual object on disk. File表示路径名,而不是磁盘上的实际对象。

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

        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM