Java资源作为文件 [英] Java resource as file

查看:79
本文介绍了Java资源作为文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中是否有办法在通过类加载器从jar检索的资源上构造File实例?

Is there a way in Java to construct a File instance on a resource retrieved from a jar through the classloader?

我的应用程序使用jar中的一些文件(默认)或从运行时指定的文件系统目录(用户输入)。我正在寻找一种一致的方式

a)将这些文件作为流加载

b)分别列出用户定义目录中的文件或jar中的目录

My application uses some files from the jar (default) or from a filesystem directory specified at runtime (user input). I'm looking for a consistent way of
a) loading these files as a stream
b) listing the files in the user-defined directory or the directory in the jar respectively

编辑:显然,理想的方法是完全远离java.io.File。有没有办法从类路径加载目录并列出其内容(包含在其中的文件/实体)?

Apparently, the ideal approach would be to stay away from java.io.File altogether. Is there a way to load a directory from the classpath and list its contents (files/entities contained in it)?

推荐答案

ClassLoader.getResourceAsStream Class.getResourceAsStream 绝对是加载资源数据的方法。但是,我不相信有任何方法可以列出类路径元素的内容。

ClassLoader.getResourceAsStream and Class.getResourceAsStream are definitely the way to go for loading the resource data. However, I don't believe there's any way of "listing" the contents of an element of the classpath.

在某些情况下,这可能根本不可能 - 例如, ClassLoader 可以根据要求的资源名称动态生成数据。如果你看一下 ClassLoader API(这基本上就是类路径机制的作用),你会发现没有任何东西可以做你想要的。

In some cases this may be simply impossible - for instance, a ClassLoader could generate data on the fly, based on what resource name it's asked for. If you look at the ClassLoader API (which is basically what the classpath mechanism works through) you'll see there isn't anything to do what you want.

如果您知道自己确实有一个jar文件,可以使用 ZipInputStream 加载它,以找出可用的内容。这意味着您将拥有不同的目录和jar文件代码。

If you know you've actually got a jar file, you could load that with ZipInputStream to find out what's available. It will mean you'll have different code for directories and jar files though.

如果首先单独创建文件,则另一种方法是包含一种清单文件包含可用资源列表。将其捆绑在jar文件中或将其作为文件包含在文件系统中,并在为用户提供资源选择之前加载它。

One alternative, if the files are created separately first, is to include a sort of manifest file containing the list of available resources. Bundle that in the jar file or include it in the file system as a file, and load it before offering the user a choice of resources.

这篇关于Java资源作为文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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