简体   繁体   中英

How to delete specific file from folder in JAVA, without deleting the folder itself?

I'm having a problem in deleting a specific file in a folder, This is what I want to happen:

I want to delete a file, having the file name of..

This is my code by the way:

try
{
    File f=new File("C://Generated Barcodes//"+file_copy.getText()+".png");//full path like c:/home/ri
    if(!f.exists())
    {
        JOptionPane.showMessageDialog(null, "Something Went Wrong!",
        " ", JOptionPane.ERROR_MESSAGE);
    }
    else
    {
        f.delete();
    }
} catch(Exception e) {
    e.printStackTrace();
}

can anyone help me out on how to do it.? It did not delete the file actually. And I guess, the delete() there, doesn't do anything. Your help is highly appreciated.

Why do you check for existence? Just try deleting, and catch with the alert. Put the error message in the catch.

try
{
    File f=new File("C:/Generated Barcodes/" + file_copy.getText() + ".png");
    boolean deleted = f.delete();
} catch(Exception e) {
    JOptionPane.showMessageDialog(null, "Something Went Wrong!",
        " ", JOptionPane.ERROR_MESSAGE);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM