Currently, I am using JxBrowser 6.14.2 to save a file. However, I found the default implementation does not meet my expectation.
Problem 1 If the file exists, then it seems to override the prev. file and does not prompt the user. [solved by the code that follows]
Problem 2 Worse still, if the file is opening, hence unable to override, no warning is raised to user. [real problem]
Therefore, I have implement the DownloadHandler provided by JxBrowser to solve problem 1, as follows:
browser.setDownloadHandler(new DownloadHandler() {
@Override
public boolean allowDownload(final DownloadItem download) {
String downloadPath = download.getDestinationFile().getPath();
final String fileType = Files.getFileExtension(downloadPath);
JFileChooser fc = new JFileChooser() {
@Override
public void approveSelection() {
String filePath = getSelectedFile().getPath();
debug_log.debug("filePath = " + filePath);
File f = new File(filePath + "." + fileType);
if (f.exists() && getDialogType() == SAVE_DIALOG) {
int result =
JOptionPane.showConfirmDialog(
this, "override file ?", "override file ?",
JOptionPane.YES_NO_CANCEL_OPTION);
switch (result) {
case JOptionPane.YES_OPTION :
break;
case JOptionPane.NO_OPTION :
return;
case JOptionPane.CLOSED_OPTION :
return;
case JOptionPane.CANCEL_OPTION :
cancelSelection();
return;
}
}
download.setDestinationFile(f);
super.approveSelection();
}
};
fc.setAcceptAllFileFilterUsed(false);
fc.setMultiSelectionEnabled(false);
fc.setFileFilter(new FileNameExtensionFilter("*." + fileType, fileType));
int returnVal = fc.showSaveDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
return true;
}
else {
return false;
}
}
});
However, the above code can solve problem 1 only, but NOT problem 2.
I am expecting JxBrowser to throw some exceptions or at least a boolean indicator to tell me that there is an error in downloading file, for example, file path specified to be saved is currently opening, therefore an exception is thrown. And what I need to do, is to catch ANY of these exceptions (e.g. IOException) thrown by JxBrowser in saving part, and tell the user, that there are errors in saving file.
Hope someone can solve my problem.
JxBrowser behaves in the same way as Google Chrome due to the fact that JxBrowser is based on Chromium engine. Google Chrome silently overrides existing file with downloaded one even if it is being edited at the moment. As a workaround I suggest, that you implement your custom Java solution and perform all necessary checks in the scope of this solution before allowing file downloading.