0
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
4

3 回答 3

1

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

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

此功能可以帮助:

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

如何判断为什么在 Java 中文件删除失败?

于 2013-02-13T06:51:40.777 回答
1

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

于 2013-02-13T06:51:01.973 回答
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();
         }
    }
}
于 2014-11-25T10:37:42.753 回答