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());
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With