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

查看:23
本文介绍了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.getResourceAsStreamClass.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天全站免登陆