简体   繁体   中英

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. I try to get the file to load in a 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"

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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