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/