[英]How to access and read a .txt file from a runnable jar
我如何加载带有可运行的.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相同的目录中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.