[英]How to open a file from within a jar file using the default application
There is the line Desktop.getDesktop().open(new File("url"))
for opening a file that is within my project folder. 有一行
Desktop.getDesktop().open(new File("url"))
用于打开我的项目文件夹中的文件。 But once I build the project as a jar, this line no longer opens the file that I want it to, even though it is compressed along with the jar. 但是,一旦我将项目构建为jar文件,即使它与jar文件一起压缩,此行也不再打开我想要它的文件。 How can I open the file once it is in the jar file?
将文件放入jar文件后,如何打开它?
Very simple use: 使用非常简单:
edit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
Desktop.getDesktop().open(new File("resources\\test.csv"));
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
This opens it with Excel. 这将使用Excel将其打开。 And I want that same effect, at least on my computer, when I click the button from the jar file.
当我单击jar文件中的按钮时,至少在我的计算机上,我希望获得同样的效果。
You need to extract first the file from your JAR file to a temporary location since the desktop application might not be able to open files inside an archive. 您首先需要将JAR文件中的文件提取到一个临时位置,因为桌面应用程序可能无法打开存档中的文件。 Using this theory, this could be a solution you seek
使用此理论,这可能是您寻求的解决方案
/*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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.