[英]Java: opening a resource (txt file) which is in a jar with OS standard application
我收到错误“ AWT-EventQueue-0 java.lang.IllegalArgumentException:URI不分层”。 -我正在尝试使用java.awt.Desktop api使用操作系统的默认应用程序打开文本文件。 -我正在运行的应用程序是从autorunning jar启动的。 我了解从文件中获取“文件”不是正确的方法,并且将其称为资源。 我仍然无法打开它,也无法弄清楚该怎么做。
open(new File((this.getClass().getResource("prova.txt")).toURI()));
有没有办法从我的应用程序中使用标准os应用程序打开资源? 谢谢 :)
您必须将文件从Jar中提取到temp文件夹中,然后打开该临时文件,就像处理Zip文件(Jar基本上是Zip文件)中的文件一样。
您不必将文件解压缩到/ tmp文件夹。 您可以使用`getClass()。getResourceAsStream()'直接读取它。 但请注意,路径取决于txt文件的位置以及类的包。 如果您的txt文件打包在jar的根目录中,请使用'“ /prova.txt”'。 (注意斜杠)。
我认为您无法使用外部应用程序打开它。 据我所知,所有安装程序都将其压缩内容提取到临时位置,然后将其删除。
但是您可以使用Class.getResource(String name)在Java代码中完成此操作
http://download.oracle.com/javase/6/docs/api/java/lang/Class.html#getResource(java.lang.String )
open(new File((this.getClass().getResource("prova.txt")).toURI()));
/**
Do you accept the License Agreement of XYZ app.?
*/
import java.awt.Dimension;
import javax.swing.*;
import java.net.URL;
import java.io.File;
import java.io.IOException;
class ShowThyself {
public static void main(String[] args) throws Exception {
// get an URL to a document..
File file = new File("ShowThyself.java");
final URL url = file.toURI().toURL();
// ..then do this
SwingUtilities.invokeLater( new Runnable() {
public void run() {
JEditorPane license = new JEditorPane();
try {
license.setPage(url);
JScrollPane licenseScroll = new JScrollPane(license);
licenseScroll.setPreferredSize(new Dimension(305,90));
int result = JOptionPane.showConfirmDialog(
null,
licenseScroll,
"EULA",
JOptionPane.OK_CANCEL_OPTION);
if (result==JOptionPane.OK_OPTION) {
System.out.println("Install!");
} else {
System.out.println("Maybe later..");
}
} catch(IOException ioe) {
JOptionPane.showMessageDialog(
null,
"Could not read license!");
}
}
});
}
}
如果您要传递的内容可以接受java.net.URL
则可以使用:
this.getClass().getResource("prova.txt")).toURI().toURL()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.