且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在资源文件夹中以字符串形式获取文件的位置

更新时间:2022-04-30 04:58:48

部署软件时,资源不会作为文件部署在文件夹中.它们被打包为应用程序jar的一部分.您可以通过从罐子内部检索它们来访问它们.类加载器知道如何从jar中检索内容,因此您可以使用类的类加载器来获取信息.

Resources, when you deploy your software, are not deployed as files in a folder. They are packaged as part of the jar of your application. And you access them by retrieving them from inside the jar. The class loader knows how to retrieve stuff from the jar, and therefore you use your class's class loader to get the information.

这意味着您不能在其上使用诸如FileReader之类的东西,也不能使用任何其他需要文件的东西.资源不再是文件.它们是装在jar中的字节束,只有类加载器才知道如何检索.

This means you cannot use things like FileReader on them, or anything else that expects a file. The resources are not files anymore. They are bundles of bytes sitting inside the jar which only the class loader knows how to retrieve.

如果资源是诸如图像等之类的东西,可以由知道如何访问资源URL的Java类使用(即,在给定其在jar中的位置时从jar中获取数据),则可以使用ClassLoader.getResource(String)方法获取URL并将其传递给处理它们的类.

If the resources are things like images etc., that can be used by java classes that know how to access resource URLs (that is, get the data from the jar when they are given its location in the jar), you can use the ClassLoader.getResource(String) method to get the URL and pass it to the class that handles them.

如果您想直接对资源中的数据进行任何操作(通常是通过从文件中读取数据来完成),则可以改用方法ClassLoader.getResourceAsStream(String).

If you have anything you want to do directly with the data in the resource, which you would usually do by reading it from a file, you can instead use the method ClassLoader.getResourceAsStream(String).

此方法返回一个InputStream,您可以像使用其他任何InputStream一样使用它-将Reader应用于它或类似的东西.

This method returns an InputStream, which you can use like any other InputStream - apply a Reader to it or something like that.

因此您可以将代码更改为:

So you can change your code to something like:

InputStream is = myClass().getResourceAsStream("res/usernames.txt");
reader = new LineNumberReader( new InputStreamReader(is) );

请注意,我使用的是Class中的getResourceAsStream()方法,而不是ClassLoader.这两个版本在jar中查找资源的方式略有不同.请阅读 Class

Note that I used the getResourceAsStream() method from Class rather than ClassLoader. There is a little difference in the way the two versions look for the resource inside the jar. Please read the relevant documentation for Class and ClassLoader.