本文介绍了如何从可运行的jar访问和读取.txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何加载带有可运行.jar文件的文本文件,当它没有被jared时,可以正常工作,但是在我打包应用程序后,它找不到该文件。这就是我用来加载文本文件的内容。

How can i load a text file with a runnable .jar file, It works fine when it's not jarred but after i jar the application it can't locate the file. Here's what i'm using to load the text file.

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中,则可以使用...

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.

这篇关于如何从可运行的jar访问和读取.txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 16:54