且构网

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

如何从可运行的jar访问和读取.txt文件

更新时间:2023-09-29 23:24:40

有两个原因。

假定文件没有存储在Jar中,则可以使用...

Assuming that the file is not stored within the Jar, you can use something like...

try (BufferedReader br = new BufferedReader(new InputStreamReader(PriceManager.class.getResourceAsStream("/prices.txt")))) {...

如果 prices.txt 文件被包结构掩埋,您需要提供从顶部/默认包到文件存储位置的路径。

If the prices.txt file is buried with the package structure, you will need to provide that path from the top/default package to where the file is stored.

如果文件位于外部class / jar文件,那么您需要确保它位于与执行jar相同的目录中。

If the file is external to the class/jar file, then you need to make sure it resides within the same directory that you are executing the jar from.