I’m having a problem getting all the selected files deleted. What I’m trying to do is after clicking “Add” whatever files are selected are moved to a new folder and are deleted in their previous folder. One file works fine. It deletes and moves the file. But more than one and only the first gets deleted. My loop is recognizing each file just not deleting them. I’m posting the actionevent. If more code is needed let me know. I’ve indicated where the problem is, so I think, so you don’t have to search the code.
public void actionPerformed(ActionEvent e) {
int returnValue = 0;
int option = 0;
File[] selectedFiles = new File[0];
if (e.getActionCommand().equals("CLOSE")) System.exit(0);
else if (e.getActionCommand().equals("ADD")) {
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
returnValue = chooser.showOpenDialog(this);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File[] file = chooser.getSelectedFiles();
try {
FileInputStream fstream = null;
FileOutputStream ostream = null;
for (int i = 0; i < file.length; i++) {
fstream = new FileInputStream(file[i]);
ostream = new
FileOutputStream(file[i].getName());
Path path = Paths.get(file[i].getPath());
byte[] fileArray;
fileArray = Files.readAllBytes(path);
listModel.add(0, file[i].getName());
selectedFilesList.setModel(listModel);
//ostream.write(fileArray, 0, fileArray.length);
}
fstream.close();
//ostream.close();
try {
for(int i = 0; i < file.length; i++) {
//**----------------------->>>PROBLEM**
Files.delete(Paths.get(file[i].getPath()));
System.out.println(file[i].getName());
}
} catch (NoSuchFileException x) {}
System.err.format("%s: no such" + " file or directory%n")
} catch (DirectoryNotEmptyException x) {
System.err.format("%s not empty%n");
} catch (IOException x) {
// File permission problems are caught here.
System.err.println(x);
} catch (Exception err) {
}
}
This could be caused by you failing to close your file streams in the first loop.
should be more like
Closing the same number of files you open.
This could be causing your problem by holding a lock on all but one of your files which would prevent deletion.
Also your catch exception block (last statement) does nothing with the error.