我怎样才能加载一个带有可运行的.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/