java - 在文件上使用 renameTo 更改内容

标签 java android path directory

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/

相关文章:

windows - msys git 和长路径

Delphi 获取文件位置

java - 带轴 JTable

java - 尝试使用 Parse 中的对象在 Android 中填充 ListView

java - 我是否应该删除继承类中未使用可空值注释的覆盖方法的可空性

ruby - Rails s 不启动服务器,没有错误消息

Java无法跳出while循环

Java:在每个数组值前面输入一个数字

java - 将对象从另一个类添加到 ArrayList

android - Volley正在获取数据,但有时会在listview中显示数据,有时不会