我正在尝试使用这段代码来完成这样的任务:
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
因此,您最终会得到 tmp1
、tmp2
和 tmpVar
这三个引用相同的 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/