您可以使用Desktop.getDesktop().open(new File(path));
这样的:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
openFile();
}
方法使用JFileChooser
并打开PDF文件:
private void openFile() throws IOException, ClassNotFoundException {
FileFilter fJavaFilter = new FileFilter();
JFileChooser fc = new JFileChooser();
fc.setDialogTitle("Open your file");
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fc.setCurrentDirectory(new File("."));
fc.setFileFilter(fJavaFilter);
int result = fc.showOpenDialog(this);
if (result == JFileChooser.CANCEL_OPTION) {
//cancel action
} else if (result == JFileChooser.APPROVE_OPTION) {
//open file using
File selectedFile = fc.getSelectedFile();
String path = selectedFile.getAbsolutePath();
File myFile = new File(path);
Desktop.getDesktop().open(myFile);
}
}
编辑
我们使用FileFilter
过滤只有我们的扩展我们需要如果你不想使用任何过滤器,你可以评论这两行:
//FileFilter fJavaFilter = new FileFilter();
//....
//fc.setFileFilter(fJavaFilter);
如果你要使用过滤器,你可以将该类添加到您的项目,或者你可以在同一个类中使用它:
class FileFilter extends javax.swing.filechooser.FileFilter {
@Override
public boolean accept(File f) {
//your filter here
return f.getName().toLowerCase().endsWith(".pdf")
|| f.isDirectory();
}
@Override
public String getDescription() {
return "Select file (*.pdf)";
}
}
什么是用于打开该文件的目的是什么?你想在你的程序中预览它还是启动外部应用程序来做一些事情? –
我想在我的程序中预览一个pdf文件.. –
但有一个想法:我希望这个项目只是为了学习;你真的不是真的在这样的系统上工作,在现实世界中使用? – GhostCat