Java:使用操作系统标准应用程序打开 jar 中的资源(txt 文件)
我收到错误“AWT-EventQueue-0 java.lang.IllegalArgumentException:URI 不是分层的”。 -我尝试使用 java.awt.Desktop api 通过操作系统的默认应用程序打开文本文件。 -我正在运行的应用程序是从自动运行的 jar 启动的。 我知道“从文件中获取文件”不是正确的方法,它被称为资源。我仍然无法打开它,也不知道该怎么做。
open(new File((this.getClass().getResource("prova.txt")).toURI()));
有没有办法从我的标准操作系统应用程序打开资源应用? 谢谢 :)
i get the error "AWT-EventQueue-0 java.lang.IllegalArgumentException: URI is not hierarchical".
-I'm trying to use the java.awt.Desktop api to open a text file with the OS's default application.
-The application i'm running is launched from the autorunning jar.
I understand that getting a "file from a file" is not the correct way and that it's called resource. I still can't open it and can't figure out how to do this.
open(new File((this.getClass().getResource("prova.txt")).toURI()));
Is there a way to open the resource with the standard os application from my application?
Thx :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您必须将文件从 Jar 提取到临时文件夹并打开该临时文件,就像处理 Zip 文件(Jar 基本上就是这样)中的文件一样。
You'd have to extract the file from the Jar to the temp folder and open that temporary file, much like you would do with files in a Zip-file (which a Jar basically is).
您不必将文件提取到 /tmp 文件夹。您可以使用“getClass().getResourceAsStream()”直接读取它。但请注意,路径取决于您的 txt 文件所在的位置以及您的类的包是什么。如果您的 txt 文件打包在 jar 的根目录中,请使用“/prova.txt”。 (注意前导斜杠)。
You do not have to extract file to /tmp folder. You can read it directly using `getClass().getResourceAsStream()'. But note that path depend on where your txt file is and what's your class' package. If your txt file is packaged in root of jar use '"/prova.txt"'. (pay attention on leading slash).
我认为您无法使用外部应用程序打开它。据我所知,所有安装程序都会将其压缩内容提取到临时位置,然后将其删除。
但是您可以在 Java 代码中使用 Class.getResource(String name)
http://download.oracle.com/javase/6/docs/api/java/lang/Class.html#getResource(java.lang.String)
I don't think you can open it with external applications. As far as i know, all installers extract their compressed content to a temp location and delete them afterwards.
But you can do it inside your Java code with Class.getResource(String name)
http://download.oracle.com/javase/6/docs/api/java/lang/Class.html#getResource(java.lang.String)
错
对
Wrong
Right
有 JarFile 和 JarEntry 类。这允许从 JarFile 加载文件。
There is JarFile and JarEntry classes from JDK. This allows to load a file from JarFile.
如果您传递给的内容可以接受
java.net.URL
这将起作用:this.getClass().getResource("prova.txt")).toURI().toURL ()
If what you're passing to can accept a
java.net.URL
this will work:this.getClass().getResource("prova.txt")).toURI().toURL()