java 使用 f.delete() 方法删除现有文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14847914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 17:36:33 来源:igfitidea点击:
Deleting an existing file using f.delete() method
提问by Surya
String book_name = book_list.getModel().getElementAt(book_list.getSelectedIndex()).toString();
System.out.println("File name : "+book_name);
File f = new File("C:\Users\Surya\Documents\NetBeansProjects\New_Doodle\Library\"+book_name);
System.out.println("Path:"+f.getAbsolutePath());
if(f.exists())
System.out.println("Book Exists");
else
System.out.println("Not Exixts");
if(f.isFile())
{
System.out.println("It is File");
}
else
System.out.println("It is Directory");
System.out.println(f.isAbsolute());
if (f.delete())
{
JOptionPane.showMessageDialog(null, "Book Deleted");
}
else
{
JOptionPane.showMessageDialog(null, "Operation Failed");
}
Output
输出
File name : `Twilight03-Eclipse.pdf`
Path: `C:\Users\Surya\Documents\NetBeansProjects\New_Doodle\Library\Twilight03-Eclipse.pdf`
Book Exists
It is File
true
Operation Failed (dialog box)
File is not deleted
回答by Aniket Inge
Use the java.nio.filepackage to find out why your delete operation fails. It gives you a detailed reason for the same.
使用java.nio.file包找出删除操作失败的原因。它为您提供了相同的详细原因。
回答by Pheonix
A deletion may fail due to one or more reasons:
由于一种或多种原因,删除可能会失败:
- File does not exist (use File#exists() to test).
- File is locked (because it is opened by another app (or your own code!).
- You are not authorized (but that would have thrown a SecurityException, not returned false!).
- 文件不存在(使用 File#exists() 测试)。
- 文件被锁定(因为它被另一个应用程序(或您自己的代码!)打开。
- 您未获得授权(但这会引发 SecurityException,而不是返回 false!)。
This function could help:
此功能可以帮助:
public String getReasonForFileDeletionFailureInPlainEnglish(File file) {
try {
if (!file.exists())
return "It doesn't exist in the first place.";
else if (file.isDirectory() && file.list().length > 0)
return "It's a directory and it's not empty.";
else
return "Somebody else has it open, we don't have write permissions, or somebody stole my disk.";
} catch (SecurityException e) {
return "We're sandboxed and don't have filesystem access.";
}
}
回答by Lokesh Kumar
public class Example {
public static void main(String[] args) {
try{
File file = new File("C:/ProgramData/Logs/" + selectedJLItem);
if(file.delete()){
System.out.println(file.getName() + " Was deleted!");
}else{
System.out.println("Delete Operation Failed. Check: " + file);
}
}catch(Exception e1){
e1.printStackTrace();
}
}
}