File dir = new File(getFilesDir(), "dir1");
dir.renameTo(new File(getFilesDir(), "dir2");
Log.d("Number of files:", dir.listFiles().length);
假设/dir1/包含 5 个文件。这段代码将打印 0。但是,如果我将代码更改为`
File dir = new File(getFilesDir(), "dir1");
dir.renameTo(new File(getFilesDir(), "dir2");
dir = new File(getFilesDir(), "dir2");
Log.d("Number of files:", dir.listFiles().length);
它将打印正确的值:5。这有什么原因吗?我使用 renameTo 后,看起来 dir 没有链接到同一目录。
最佳答案
原因是在您的第一个代码中 dir
仍然指向目录 dir1
而不是 dir2
。
但是,在下面的代码中:
File dir = new File(getFilesDir(), "dir1");
dir.renameTo(new File(getFilesDir(), "dir2");
dir = new File(getFilesDir(), "dir2");
Log.d("Number of files:", dir.listFiles().length);
dir
现在指向 dir2
,因此您获得了正确的值。
我建议您避免使用 Java 的 File.renameTo(),因为它是有问题的,尤其是在 Windows 上。正如 API 文档所述:
Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.
您可以使用 apache.commons.io 库,其中包括 FileUtils.moveFile() 或 JDK 7 中的 Files.move() 方法。
关于java - 在文件上使用 renameTo 更改内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45755728/