使用f.delete()方法删除现有文件

时间:2013-02-13 06:40:32

标签: java file

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");
}

输出

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

3 个答案:

答案 0 :(得分:1)

使用java.nio.file包找出删除操作失败的原因。它给出了相同的详细原因。

答案 1 :(得分:1)

由于一个或多个原因,删除可能会失败:

  • 文件不存在(使用File#exists()进行测试)。
  • 文件被锁定 (因为它是由另一个应用程序(或您自己的代码!)打开的。
  • 你不是 授权(但是会抛出SecurityException,而不是 返回假!)。

此功能可以提供帮助:

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.";
    }
}

How to tell why a file deletion fails in Java?

答案 2 :(得分:0)

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();
         }
    }
}