【发布时间】:2017-08-31 10:41:15
【问题描述】:
目前,我正在使用 JxBrowser 6.14.2 来保存文件。但是,我发现默认实现不符合我的期望。
问题 1 如果文件存在,那么它似乎会覆盖上一个。文件并且不提示用户。 【通过后面的代码解决】
问题 2 更糟糕的是,如果文件正在打开,因此无法覆盖,则不会向用户发出警告。 [真正的问题]
因此,我实现了JxBrowser提供的DownloadHandler来解决问题1,如下:
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;
}
}
});
但是,上面的代码只能解决问题1,不能解决问题2。
我希望 JxBrowser 会抛出一些异常或至少一个布尔指示器来告诉我下载文件时出现错误,例如,指定要保存的文件路径当前正在打开,因此抛出异常。而我需要做的是捕捉JxBrowser在保存部分抛出的任何这些异常(例如IOException),并告诉用户保存文件时出现错误。
希望有人能解决我的问题。
【问题讨论】:
标签: java file exception-handling jxbrowser