gpt4 book ai didi

java - 重命名目录时重命名文件

转载 作者:搜寻专家 更新时间:2023-11-01 02:23:44 24 4
gpt4 key购买 nike

尝试重命名目录名和文件名。

try
{
File dir = new File("DIR");
dir.mkdir();
File file1 = new File(dir,"myfile1.txt");
file1.createNewFile();
File file2 = new File(dir,"myfile2.txt");
file2.createNewFile();

dir.renameTo(new File("myDIR"));
System.out.print(file1.renameTo(new File(dir,"myf1.txt")));
}
catch(IOException ie)
{

}

但是,只有目录被成功重命名,而文件名没有被成功重命名。
这些操作不能同时进行吗?

最佳答案

这是因为您的 dirfile1file2 指向旧路径。

执行完这些行后,

File dir = new File("DIR");
dir.mkdir();
File file1 = new File(dir,"myfile1.txt");
file1.createNewFile();
File file2 = new File(dir,"myfile2.txt");
file2.createNewFile();

这些将是变量引用的路径,

dir = "DIR" // Exists
file1 = "DIR\myfile1.txt" //Exists
file2 = "DIR\myfile2.txt" //Exists

执行后,

    dir.renameTo(new File("myDIR"));            

变量引用的路径还是一样,

dir = "DIR" // Doesn't exist anymore because it's moved.
file1 = "DIR\myfile1.txt" // Doesn't exist anymore because it's moved along with dir.
file2 = "DIR\myfile2.txt" // Doesn't exist anymore because it's moved along with dir.

所以,当你打电话时,

    System.out.print(file1.renameTo(new File(dir,"myf1.txt")));

您正在对一个不存在的文件和一个也不存在的目录调用 renameTo()。所以它注定会失败。

即使您在 dirfile1file2 上调用 .exists() 方法,它只会返回 false

关于java - 重命名目录时重命名文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31494111/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com