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

标签 java bufferedreader filereader

我怎样才能加载一个带有可运行的.jar文件的文本文件,当它没有被jarred时它工作得很好,但是在我jar了应用程序之后它无法找到该文件。这是我用来加载文本文件的内容。

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class PriceManager {

    private static Map<Integer, Double> itemPrices = new HashMap<Integer, Double>();

    public static void init() throws IOException {
        final BufferedReader file = new BufferedReader(new FileReader("prices.txt"));
        try {
            while (true) {
                final String line = file.readLine();
                if (line == null) {
                    break;
                }
                if (line.startsWith("//")) {
                    continue;
                }
                final String[] valuesArray = line.split(" - ");
                itemPrices.put(Integer.valueOf(valuesArray[0]), Double.valueOf(valuesArray[1]));
            }
            System.out.println("Successfully loaded "+itemPrices.size()+" item prices.");
        } catch (final IOException e) {
            e.printStackTrace();
        } finally {
            if (file != null) {
                file.close();
            }
        }
    }

    public static double getPrice(final int itemId) {
        try {
            return itemPrices.get(itemId);
        } catch (final Exception e) {
            return 1;
        }
    }

}

感谢您的所有帮助。

最佳答案

这有两个原因。该文件现在要么嵌入到 Jar 中,要么没有...

假设文件没有存储在 Jar 中,您可以使用类似...

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

如果 prices.txt 文件与包结构一起隐藏,您将需要提供从顶部/默认包到文件存储位置的路径。

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

关于java - 如何从可运行的 jar 访问和读取 .txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25599138/

相关文章:

java - 无法使用java解析.conf文件

java - 我的问题是关于 find(Node root ,int level) 方法。这是关于在给定二叉树中查找最深节点的代码

java - 在java中使用相同的扫描仪

java - C# 中的 readInt16() 与 java 中的 readShort()

java - 五分钟内仅更新文件中的新内容

java - 如何使用 Vertx 和 Redis 持续监听消息?

java - Hibernate Criteria - 日期比较未返回正确结果

java newbie : reading in a file for word search code. .add() 和 .toArray() 给我错误

Java BufferedReader 只读取两行

readline 不接受 Java 输入