如何使用默认应用程序从 jar 文件中打开文件



有一行Desktop.getDesktop().open(new File("url"))用于打开我的项目文件夹中的文件。但是一旦我将项目构建为 jar,此行就不再打开我想要的文件,即使它与 jar 一起压缩。文件进入 jar 文件后如何打开

?非常简单的使用:

edit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
Desktop.getDesktop().open(new File("resources\test.csv"));
} catch (IOException e1) {
e1.printStackTrace();
}
}
});

这将使用 Excel 打开它。我想要同样的效果,至少在我的电脑上,当我点击jar文件中的按钮时。

您需要首先将文件从 JAR 文件提取到临时位置,因为桌面应用程序可能无法打开存档中的文件。使用这个理论,这可能是你寻求的解决方案

/*You can use this section into your function and import the right packages
* Then include this bit in the function that you intent to perform what you have described in your question
*/
//I assume your file is of extention '.ext'
String inputFile = "path/youtfile.ext";
Path tempOutput = Files.createTempFile("TempManual", ".ext");
tempOutput.toFile().deleteOnExit();
System.out.println("tempOutput: " + tempOutput);
try (InputStream is = YOURCLASS.class.getClassLoader().getResourceAsStream(inputFile)){
Files.copy(is, tempOutput, StandardCopyOption.REPLACE_EXISTING);
}
Desktop.getDesktop().open(tempOutput.toFile());

最新更新