任何从JAR获取File对象的方法 [英] Any way to get a File object from a JAR

查看:96
本文介绍了任何从JAR获取File对象的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含使用外部模型文件的API的JAR文件。我想将模型文件包含在JAR本身中,以便更容易用于其他开发人员。 API只接受File对象,有没有办法做到这一点?我已经尝试过以下操作,但它们都失败了:

I have a JAR file that contains an API that uses external model files. I would like to include the model files in the JAR itself so it easier to use for other developers. The API will accept a File object only, is there any way to do this? I have already tried the following, and they have failed:


  • 使用class.getResourceAsStream()。如果API接受了InputStream,这将起作用。
  • 解析类路径并尝试从条目构建(JAR将显示为app.jar)
  • Using class.getResourceAsStream(). This would work if the API accepted an InputStream.
  • Parsing the classpath and trying to build from the entries (the JAR will show as app.jar)

我想一个选项是使用getResourceAsStream并将文件移动到HDD上的永久位置,但我不喜欢这个选项。必须有更好的东西,任何想法?

I suppose an option is to use getResourceAsStream and move the files to a permanent location on the HDD but, I do not like this option. There has to be something better, any thoughts?

推荐答案

.jar文件中的资源不是操作系统可以通过普通文件访问API直接访问它们的文件。

Resources in a .jar file are not files in the sense that the OS can access them directly via normal file access APIs.

因为 java.io.File 正好代表那种文件(即看起来像文件的东西)到OS),它不能用于引用.jar文件中的任何内容。

And since java.io.File represents exactly that kind of file (i.e. a thing that looks like a file to the OS), it can't be used to refer to anything in a .jar file.

可能的解决方法是将资源提取到临时文件并引用使用文件

A possible workaround is to extract the resource to a temporary file and refer to that with a File.

请注意,通常应尝试处理文件的API来处理 InputStream / OutputStream 以及允许此类操作成功。

Note that generally APIs that try to handle files should be written to handle InputStream/OutputStream as well to allow this kind of operations to suceed.

这篇关于任何从JAR获取File对象的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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