I am copying directories and files from one windows server to another windows server using Swing and that works fine. I want to have a Joption Messagedialog pop up when the windows server goes down unexpectedly while copying so gave it in the catch block but it never dispays the pop up when the server goes down(I restart the windows server manually while copying but cannot see the pop up). Can someone help and here is the code
try {
textarea.append("Copying " + sourceFile.getAbsolutePath()
+ " to " + targetFile.getAbsolutePath());
is = new BufferedInputStream(new FileInputStream(sourceFile));
bos = new BufferedOutputStream(new FileOutputStream(targetFile));
long fileBytes = sourceFile.length();
long soFar = 0;
int theByte;
while ((theByte = bis.read()) != -1) {
bos.write(theByte);
setProgress((int) (copiedBytes++ * 100 / totalBytes));
publish((int) (soFar++ * 100 / fileBytes));
}
bis.close();
bos.close();
publish(100);
textarea.append(" Done!\n");
} catch (Exception excep) {
task.cancel(true);
bos.flush();
bis.close();
bos.close();
jf2 = new JFrame();
jf2.setSize(401, 401);
jf2.setDefaultCloseOperation(jf2.EXIT_ON_CLOSE);
JOptionPane.showMessageDialog(jf2,
"The Server is not accessible or it may be down because of Network Issue",
"ERROR", JOptionPane.ERROR_MESSAGE);
} finally {
if (bis != null) {
bis.close();
}
if (bos != null) {
bos.close();
}
}
Your try-catch is a little akward.
You try and close the streams on the event of an exception AND within the
finallyblock.Finally is guaranteed to be called regardless, so you can save yourself some code by using it to close of the steams..
It appears that your code is using a
SwingWorker, but you calltextarea.append(" Done!\n")within it. This is VERY, VERY bad.Your
processmethod needs to be capable of doing this…Basically when youprocessreceives100, it should be capable of updating the text area.You could also allow the exception to handled else where, allowing the
doInBackgroundmethod to throw the exception. This would allow you to use thedonemethod and thegetmethod to determine if an exception has occurred, the added benefit of which isdoneis called within the EDT