Deleting file with extension in JAVA
This is my piece of code. With this, I select drive, say drive F in this case. Then on execution I try to delete a file inside that folder, although the file (if entered correctly) is deleted, but delete () returns false. May I know why this is 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());
}
source to share
Your problem is that you are calling a fs.delete()
second time after deleting it. Since it no longer exists, it cannot be deleted.
Just call the boolean you set earlier:
System.out.println("Successful/unsucceful: " + fs.getName() + "..." + dele);
In addition, the same as the side. I would just use fs.getName().equals(delFile.getName())
instead of yourcompareTo
source to share
Because you are calling delete
twice. The second time it is mistaken, since it was deleted the first time.
Change this
System.out.println("Successful/unsucceful: " + fs.getName() + "..." + fs.delete());
to
System.out.println("Successful/unsucceful: " + fs.getName() + "..." + dele);
source to share