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

java.nio.fileパッケージを使用して、削除操作が失敗した理由を調べてください。それはあなたに同じ詳細な理由を与えます。

于 2013-02-13T06:51:01.973 に答える
1

次の 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 に答える