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

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

问题描述

Desktop.open(File 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 is not hierarchy.

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天全站免登陆