My Java Windows application keeps data for a particular problem in a file aProblem.db that is in a directory (folder) of the same name, e.g., Documents\MyApplication\aProblem\aProblem.db. I would like the user to be able to delete aProblem without leaving the application. So the aProblem.db file has to be deleted, and IF aProblem directory is left empty it too should be deleted. Because FileChooser does not allow file deletion (at least from my reading of the documentation) I built my own dialog with a select box, and Ok button, and a Cancel button. The select box is populated by searching MyApplication for all directories x containing a file x.db.
The code below is the deletion part, after the user has made a selection and clicked OK. It works except for when the directory is open in Windows Explorer, when an exception is thrown when directory delete is attempted. I know it's because Explorer has a lock on it, but I'd like to avoid asking the user to close it in the Explorer and try again. Is this possible?
NOTE:I use JFileChooser.APPROVE_OPTION, but DO NOT use JFileShooser.
int resp = dialog.showOpenDialog();
if(resp == JFileChooser.APPROVE_OPTION){
strConcoursFolderPath = dialog.getSelectedFolderFullPath();
int response = yesNoDialog("Do you really want to delete " + strConcoursFolderPath + "?");
if(response == JOptionPane.YES_OPTION) {
File dir = new File(strConcoursFolderPath);
boolean dirExist = dir.exists() && dir.isDirectory();
if(dirExist) {
String strDbFile = dialog.getSelectedFolderName() + ".db";
File db = new File(dir + "\\" + strDbFile);
if(db.exists()) db.delete();
File[] listOfFiles = dir.listFiles();
if(listOfFiles.length == 0) dir.delete();
}
}
} else {
//okDialog("Cancel button clicked");
}