java - 重命名时文件不会被删除

标签 java

String namePlaylist = JOptionPane.showInputDialog("Enter Playlist name :");
File inPlayList = new File(namePlaylist);
String newName = JOptionPane.showInputDialog("Enter Playlist name :");//for new name
File newF = new File(newName);
inPlayList.renameTo(newF);
File x = new File(namePlaylist);
x.delete();

它将根据用户输入创建并重命名文件。但执行后这两个文件仍然存在。我尝试使用 delete() 但它也不起作用。

最佳答案

如 Java 文档中所述

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.

所以这个方法返回一个 boolean 值。您应该检查重命名是否成功。

我认为你应该使用Files::move相反。

这是一个关于如何使用 Java NIO.2 执行此操作的小示例:

String namePlaylist = JOptionPane.showInputDialog("Enter Playlist name :");
Path playList = Paths.get(namePlaylist);
if (Files.exists(playList)) {
    String newName = JOptionPane.showInputDialog("Enter Playlist name :");
    Path renamed = Paths.get(newName);
    try {
        Files.move(playList, renamed, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

使用 IO:

String namePlaylist = JOptionPane.showInputDialog("Enter Playlist name :");
File inPlayList = new File(namePlaylist);
if (inPlayList.exists()) {
    String newName = JOptionPane.showInputDialog("Enter Playlist name :");
    File newF = new File(newName);
    if (!newF.exists()) {
        boolean succeeded = inPlayList.renameTo(newF);
        if (!succeeded) {
            JOptionPane.showMessageDialog(null, "Renaming failed.");
        }
    }
}

关于java - 重命名时文件不会被删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33083498/

相关文章:

java - 使用处理程序在 eclipse 4.x 中打开 eclipse 3.x View

java - 从库中识别新类型

java - weblogic Server10.6中EJB定时器异常

java - Apache common-email lib - TLS 显示警告

java - hibernate 失去连接

java - 如何使用TSPlib解决旅行商问题(TSP)

java - 实体和DTO之间的区别

java - opencsv转义单引号和双引号

java - 将 "const"变量传递给 Java 中的方法

java - 使用大量已实现的接口(interface)