简体   繁体   中英

Data reading in a jar File (in Java) and counting files

So here is my problem (I read the other answers, but didn't quite get it).

In a group of 4, we have created a game in Java as a University Project. Part of this is creating a *.jar File via Ant. There is several GameBoards saved in GameBoardx.txt Data where x is the number. We want to randomly select one of those. Therefore, every time a GameBoard is loaded, the files in the GameBoard directory are counted in order to generate a random number in the correct range. Our code works perfectly fine when running it from Eclipse. It fails to run from the *.jar File and exits with a NullPointerException.

int number = 0;
int fileCount = new File(new File("").getAbsolutePath()+"/GameBoards/").listFiles().length;
Random rand = new Random();
number = rand.nextInt(fileCount);

These Files are read later on using this:

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();

The rest of the code works with the *.jar File and the *.txt Files are included in it.

The solutions I found were not good for us, because the code has to work with the *.jar File as well as just starting it from Eclipse to pass the test.

What's the solution here to make in work in both?

Problem here is you can not read content of a Jar using File , you shall use java.nio classes to deal with this.

First of all you can read/get count of files from Jar/normal folder by using FileSystem , Path and FileVisitor classes:

Following code will work for both jar as well as 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());

Following is the code for PathVisitor class

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;
    }
}

And then you shall read content of specific file by using 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);
    }

Hope this resolves your concerns and helps you in right direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM