所以这是我的问题(我阅读了其他答案,但不太明白)。
在 4 人小组中,我们用 Java 创建了一个游戏作为大学项目。其中一部分是通过 Ant 创建 *.jar 文件。 GameBoardx.txt 数据中保存了多个 GameBoard,其中 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 启动它才能通过测试。
这里的解决方案是什么?
最佳答案
这里的问题是你无法使用File
读取Jar的内容,你应该使用java.nio
类来处理这个问题。
首先,您可以使用 FileSystem
、Path
和 FileVisitor
类从 Jar/normal 文件夹中读取/获取文件数量:
以下代码适用于 jar
以及 IDE
ClassLoader sysClassLoader = ClassLoader.getSystemClassLoader();
URI uri = sysClassLoader.getResource("GameBoards").toURI();
Path gameBoardPath = null;
if (uri.getScheme().equals("jar")) {
FileSystem fileSystem = FileSystems.newFileSystem(uri,
Collections.<String, Object> emptyMap());
gameBoardPath = fileSystem.getPath("/GameBoards");
} else {
gameBoardPath = Paths.get(uri);
}
PathVisitor pathVistor = new PathVisitor();
Files.walkFileTree(gameBoardPath, pathVistor);
System.out.println(pathVistor.getFileCount());
以下是 PathVisitor
类的代码
class PathVisitor extends SimpleFileVisitor<Path> {
private int fileCount = 0;
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
fileCount++;
return FileVisitResult.CONTINUE;
}
public int getFileCount() {
return fileCount;
}
}
然后使用ClassLoader#getResourceAsStream
读取特定文件的内容
// ADD your random file picking logic here based on file Count to get boardNum
int boardNum = 1;
InputStream is = sysClassLoader.getResourceAsStream("GameBoards/Board" + boardNum + ".txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
while((line=reader.readLine())!=null) {
System.out.println(line);
}
希望这能解决您的疑虑并帮助您朝正确的方向发展。
关于java - 读取 jar 文件中的数据(Java 中)并对文件进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36868944/