简体   繁体   English

如何在与所加载的类无关的Jar中加载文件

[英]How to load a File within a Jar that is not relative to the Class its loaded from

I am trying to load a file that is within a jar file. 我正在尝试加载jar文件中的文件。 I try to get the file to load in a BufferedReader. 我尝试将文件加载到BufferedReader中。 For example: 例如:

BufferedReader br = new BufferedReader(new FileReader(fileName));

where fileName is my string from the root of the Jar file: something like this "resources/text.txt" 其中,fileName是我从Jar文件根目录开始的字符串:类似于“ resources / text.txt”

I am having a hard time finding out how to make this happen. 我很难找到如何做到这一点。 Obviously FileReader will not work since it reads from the file system. 显然,FileReader无法正常工作,因为它是从文件系统读取的。

Anyone that can help me out? 有人可以帮助我吗?

Use the classloader to get the resource as a stream . 使用类加载器将资源作为流获取

BufferedReader br = new BufferedReader(new InputStreamReader(MyClass.class.getClassLoader().getResourceAsStream("/resources/text.txt"), "utf-8");

Note that you need to specific the correct character encoding for the content. 请注意,您需要为内容指定正确的字符编码。

如果尝试访问与正在运行的程序相同的jar中的文件,则应使用

final InputStream inputStream = ClassName.class.getResourceAsStream(fileName);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM