重命名时不删除文件

时间:2015-10-12 14:20:15

标签: 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(),但它也不起作用。

2 个答案:

答案 0 :(得分:1)

如Java文档中所述

  

此方法行为的许多方面本质上都依赖于平台:重命名操作可能无法将文件从一个文件系统移动到另一个文件系统,它可能不是原子的,并且如果文件具有目标抽象路径名已存在。应始终检查返回值以确保重命名操作成功。

因此,此方法返回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.");
        }
    }
}

答案 1 :(得分:0)

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