gpt4 book ai didi

java - 如何交换目录中的文件名?

转载 作者:太空宇宙 更新时间:2023-11-04 12:39:08 25 4
gpt4 key购买 nike

我正在尝试使用这段代码来完成这样的任务:

    File copyOfFirstVar= tmp1;
File copyOfSecondVar= tmp2;

File tmpVar = File.createTempFile("temp", "tempFile");

tmp1.renameTo(tmpVar)
tmp2.renameTo(copyOfFirstVar);
tmp1.renameTo(copyOfSecondVar);

其中 tmp1 和 tmp2 是来自 File 类 -> 我想要重命名的文件的对象,但这没有任何作用。

最佳答案

正如评论中所说,您多次引用同一个File(即temp文件)。

自:

File copyOfFirstVar= tmp1;
File copyOfSecondVar= tmp2;

你的逻辑变成:

tmp1.renameTo(tmpVar);  // now tmp1 and tmpVar are references to the same file
tmp2.renameTo(tmp1); // now tmp2 and tmp1 are references to the same file
tmp1.renameTo(tmp2); // see above

因此,您最终会得到 tmp1tmp2tmpVar 这三个引用相同的 File

您应该避免使用File引用进行交换,只需使用路径作为String

File copyOfFirstVar= tmp1;
File copyOfSecondVar= tmp2;

String firstPath = copyOfFirstVar.getAbsolutePath();
String secondPath = copyOfSecondVar.getAbsolutePath();

File tmpVar = File.createTempFile("temp", "tempFile");

tmp1.renameTo(tmpVar);
tmp2.renameTo(new File(firstPath));
tmp1.renameTo(new File(secondPath));

另请注意,正如其他人指出的那样,如果目标 File 存在,则 renameTo 将失败。

关于java - 如何交换目录中的文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37004950/

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