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

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

问题描述

我有一个 JAR 文件,其中包含一个使用外部模型文件的 API.我想在 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 完全代表那种文件(即对操作系统来说看起来像文件的东西),它不能用于引用 .java 文件中的任何内容.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.

一种可能的解决方法是将资源提取到一个临时文件中,并使用 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天全站免登陆