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

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
Community
  • 1
  • 1
Surya
  • 71
  • 1
  • 1
  • 6

3 Answers3

1

Use the java.nio.file package to find out why your delete operation fails. It gives you a detailed reason for the same.

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
1

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!).

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

How to tell why a file deletion fails in Java?

Community
  • 1
  • 1
Pheonix
  • 6,049
  • 6
  • 30
  • 48
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();
         }
    }
}
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Lokesh Kumar
  • 801
  • 2
  • 8
  • 13