my program is meant to load an image, resize it, save it, send it to FTP server and then delete resized image. Full code – HERE
The problem I am encountering is after pressing a finish button from the file named AddBreedBuilder.java: program sends resized file to server, freeze for ~1 sec, and it is trying to remove resized file (but it is not possible).
I tried to use (at the moment this part is deleted from java file, line 165): File fileToDelete = new File(imgPath);
but
boolean success = fileToDelete.delete();success
is always false
. Only way to delete this file is to not run sendToFTP()
.
From what I think, my program is using this file during file delete operation, so it cannot be deleted.
My question is: is it possible to delay file delete till program unfreeze?
Or maybe there is way to send resized file without saving it?
2
Answers
That is correct.
The reason is that your
sendToFTP
method opens the file that it is sending to the server, but it doesn’t (ever) close it. Since the file is still open, Windows won’t let the app delete itSolution: modify your
sendToFTP
method so that theFileInputStream
is always closed.Beyond the questions you’ve asked, a few things are wrong with the code itself and it affects the answers to the questions. I’ll address these later. However, to directly address your questions first:
Yes. You can do this by starting a new thread that handles the FTP transmission, since the transmission is initiated as the result of a GUI event, so that it doesn’t freeze your application. (The event dispatch thread that handles the GUI only starts the new thread without waiting for it to finish.) In
sendToFTP()
, do:Then in the calling function,
buildAdd()
You can definitely send the file (more precisely, the file contents) without having to produce the file at all. You can instead supply the
BufferedImage
directly to thesendToFTP()
method, and then transform that to the requiredInputStream
forclient.storeFile()
. In this case you don’t even need to store the file at all in the first place if you don’t need it on the local machine.Then in the calling function,
buildAdd()
Notice the change in the signature of the second version of
sendToFTP()
. You could play with this idea in a different way, and rather replace the file writing call inbuildAdd()
with thisInputStream
, and then pass the stream tosendToFTP()
.Note
You can use the try-with-resources idiom for ensuring the streams used above are automatically closed: see
here for example.
Other issues addressed:
use the final name the first time.
buildAdd()
).