Question

I've been trying to delete a file from a jlist on the press of a button but it always seems to fail. I know the path that I'm getting from the jlist is correct because I am able to open the file and I've also tried using this code to delete a file using an absolute path. Does anybody see any errors here or something I'm doing wrong?

JButton btnDeleteLog = new JButton("Delete Log");
btnDeleteLog.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        try{
            File file = new File("C:/ProgramData/Logs/" + selectedJLItem);
            file.delete();
            if(file.delete()){
                System.out.println(file.getName() + " Was deleted!");
                ClientWindow.console(file.getName() + " Was Deleted Successfully!");
            }else{
                System.out.println("Delete Operation Failed. Check: " + file);
                ClientWindow.console("Failed To Delete " + file.getName());
            }
        }catch(Exception e1){
            e1.printStackTrace();
        }
    }
});
Was it helpful?

Solution

You are trying to delete a file twice.

First:

file.delete();

Second:

if(file.delete()){ // some processing here }

Instead, try to do so:

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

This is the right way and you get:

Example.txt Was deleted!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top