我正在制作一个使用文本文件的程序。我需要这样做,以便程序可以使用其jar文件从不同的计算机运行。问题是我无法找到文本文件的正确文件路径。我尝试过使用getResource()
,但它仍然无法正常工作。这是代码:
public class Params {
public static void init() {
hsChartSuited = new int[13][13];
file = new File(Params.class.getResource("HandStrengthDataSuited.txt").getFile());
try {
Scanner input = new Scanner(file);
for (int i = 0; i < hsChartSuited.length; i++) {
for (int j = 0; j < hsChartSuited[i].length; j++) {
hsChartSuited[i][j] = Integer.parseInt(input.next()) - 20;
}
}
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
}
HandStrengthDataSuited.txt
是我项目的src文件夹中的文件。它也位于文件夹之外,也位于项目的主目录中。我已经尝试打印绝对文件路径,这就是我得到的:
/Users/MyUsername/file:/Users/MyUsername/Documents/Homework_Soph_2012/Computer%20Science/HoldEm/dist/HoldEm.jar!/holdem/HandStrengthDataSuited.txt
我需要获取的文件路径是
/Users/MyUsername/Documents/Homework_Soph_2012/Computer%20Science/HoldEm/holdem/HandStrengthDataSuited.txt
有谁知道这里的问题是什么?
答案 0 :(得分:0)
如果您的文件位于src文件夹中,
class Tools {
public static InputStream getResourceAsStream(String resource)
throws FileNotFoundException
{
String stripped = resource.startsWith("/") ? resource.substring(1) : resource;
InputStream stream = null;
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader != null) {
stream = classLoader.getResourceAsStream(stripped);
}
if (stream == null) {
stream = Tools.class.getResourceAsStream(resource);
}
if (stream == null) {
stream = Tools.class.getClassLoader().getResourceAsStream(stripped);
}
if (stream == null) {
throw new FileNotFoundException("Resource not found: " + resource);
}
return stream;
}
}
使用:
reader = new BufferedReader(new InputStreamReader(getResourceAsStream("org/paulvargas/resources/file.txt"), "UTF-8"));