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

标签 java

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

    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/

相关文章:

java - 将批量操作作为中间流操作运行

java - Netbeans HelloWorld Java Rest 示例的问题

java - 从 SFTP 下载 ZIP 文件并将其保存到本地目录

java - Spring boot基础应用: field NotesRepository required a bean of type 'com.demo.NotesRepository' that could not be found

java - 在数组列表中查找索引总是出现在-1

java - 从 SQLite 数据库加载数据到 ListView

java - 在 TreeSet 和 TreeMap 中使用 hashCode() 和 equals()

java - 在 while(resultSet.next()) 循环中调用 JComboBox#addItem() 最终只有 1 个项目

java - hibernate 5 java.lang.NoSuchMethodError org.jboss.logging.Logger.debugf

java - 如何将证书添加到 Openshift 中的 Java CA 证书存储(cacerts)?