【发布时间】:2016-08-20 12:27:02
【问题描述】:
所以这是我的问题(我阅读了其他答案,但不太明白)。
在一个 4 人小组中,我们用 Java 创建了一个游戏作为大学项目。其中一部分是通过 Ant 创建一个 *.jar 文件。 GameBoardx.txt 数据中保存了几个游戏板,其中 x 是数字。我们想随机选择其中之一。因此,每次加载 GameBoard 时,都会对 GameBoard 目录中的文件进行计数,以便生成正确范围内的随机数。我们的代码在 Eclipse 中运行时运行良好。它无法从 *.jar 文件运行并以 NullPointerException 退出。
int number = 0;
int fileCount = new File(new File("").getAbsolutePath()+"/GameBoards/").listFiles().length;
Random rand = new Random();
number = rand.nextInt(fileCount);
这些文件稍后会使用这个来读取:
static String fileName = new File("").getAbsolutePath();
static String line = null;
boolean verticalObstacles[][] = new boolean[16][17];
int currentLine = 1;
try {
FileReader fileReader = new FileReader(fileName+"/GameBoards/Board"+boardNumber+".txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null){
if (currentLine <17){
for (int i=0; i<17; i++){
if (line.charAt(i) == '1'){
verticalObstacles[currentLine-1][i] = true;
} else {
verticalObstacles[currentLine-1][i] = false;
}
}
}
currentLine ++;
}
bufferedReader.close();
其余代码使用 *.jar 文件,其中包含 *.txt 文件。
我发现的解决方案对我们不利,因为代码必须与 *.jar 文件一起使用,并且只需从 Eclipse 启动它才能通过测试。
在这两种情况下都有什么解决方案?
【问题讨论】:
-
您应该将您的 GameBoards 目录与 jar 之外的文件一起保存
-
那不适用。我们被要求创建 jar 文件的原因是为了让我们有一个可以发送并供人们使用的单个文件,而无需任何额外的工作。