How to access and read a .txt file from a runnable jar

白昼怎懂夜的黑 提交于 2020-03-06 04:18:09

问题


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

}

Thanks for any and all help.


回答1:


There are two reasons for this. Either the file is now embedded within the Jar or it's not...

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")))) {...

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.

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.




回答2:


if this is your package structure:

Correct way of retrieving resources inside runnable or.jar file is by using getResourceAsStream.

InputStream resourceStream =  TestResource.class.getResourceAsStream("/resources/PUT_Request_ER.xml");

If you do getResource("/resources/PUT_Request_ER.xml"), you get FileNotFoundException as this resource is inside compressed file and absolute file path doesn't help here.



来源:https://stackoverflow.com/questions/25599138/how-to-access-and-read-a-txt-file-from-a-runnable-jar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!