Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting a file with extension name in JAVA

Tags:

java

This is my piece of code. With this I am picking a drive, say F drive in this case. Then on executing the I am trying to delete a file inside that folder, although the file(when correctly entered) is being deleted, yet the delete() is returning false. May I know why so?

System.out.println("Enter file to be deleted:");
String del = sc.nextLine(); //give file name as string with extension
File delFile = new File(del); //convert string to file type
for (File fs: listOfFiles) {
    if (fs.getName().compareTo(delFile.getName()) == 0) {
        System.out.println(fs.getName());
        System.out.println("Inside loop");
        boolean dele = fs.delete();
        System.out.println("Successful/unsucceful: " + fs.getName() + "..." + fs.delete());
    } else
        System.out.println("invalid : " + fs.getName());
}
like image 842
Shailja Avatar asked Dec 13 '25 05:12

Shailja


1 Answers

Your problem is, that you call fs.delete() a second time after it was already deleted. Because it doesn't exist anymore, it can't be deleted

Just call the boolean value you've set before:

System.out.println("Successful/unsucceful: " + fs.getName() + "..." + dele);

Also, just as a sidenote. I would just use fs.getName().equals(delFile.getName()) instead of your compareTo

like image 156
Christian Avatar answered Dec 14 '25 19:12

Christian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!