JAR中的Java Desktop.open(File f)引用文件? [英] Java Desktop.open(File f) reference file within JAR?

查看:258
本文介绍了JAR中的Java Desktop.open(File f)引用文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Desktop.open(文件f)可以引用位于JAR中的文件吗?

It is possible to for Desktop.open(File f) to reference a file located within a JAR?

我尝试使用 ClassLoader.getResource(String s),将其转换为URI,然后从中创建文件。但这导致 IllegalArgumentException:URI不是分层的

I tried using ClassLoader.getResource(String s), converting it to a URI, then creating a File from it. But this results in IllegalArgumentException: URI is not hierarchical.

URL url = ClassLoader.getSystemClassLoader().getResource(...);
System.out.println("url=" + url);    // url is valid
Desktop.getDesktop().open(new File(url.toURI()));

可能性是 JavaRanch的答案,即从JAR内的资源创建一个临时文件 - 不是很优雅。

A possibility is the answer at JavaRanch, which is to create a temporary file from the resource within the JAR – not very elegant.

这是在Windows XP上运行。

This is running on Windows XP.

推荐答案

文件里面的.jar文件不是操作系统的文件。它们只是.jar文件的某个区域,通常是压缩的。操作系统无法将它们作为单独的文件进行寻址,因此无法以这种方式显示。

"Files" inside .jar files are not files to the operating system. They are just some area of the .jar file and are usually compressed. They are not addressable as separate files by the OS and therefore can't be displayed this way.

Java本身有一种通过某种URI引用这些文件的简洁方法(你通过使用 getResource()来实现,但这完全是特定于Java的。

Java itself has a neat way to referring to those files by some URI (as you realized by using getResource()) but that's entirely Java-specific.

如果你想要一些外部应用程序要访问该文件,您有两种可能的解决方案:

If you want some external application to access that file, you've got two possible solutions:


  1. 提供一些标准化的方式来访问该文件或

  2. 使应用程序能够处理打包在.jar(或.zip)文件中的文件。

通常2实际上不是一个选项(除非另一个应用程序也是用Java编写的,在这种情况下它很容易)。

Usually 2 is not really an option (unless the other application is also written in Java, in which case it's rather easy).

选项1通常只需写入一个临时文件并引用它。或者,您可以启动一个小型Web服务器并通过某个URL提供该文件。

Option 1 is usually done by simply writing to a temporary file and referring to that. Alternatively you could start a small web server and provide the file via some URL.

这篇关于JAR中的Java Desktop.open(File f)引用文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆