Sayed Hajaj
Sayed Hajaj

Reputation: 62

Access files and folders in Jar files

There are many similar questions to this but this is not a duplicate. This is similar to "Can't access files in Jar file" but there is a slight difference. With a lot of experimentation and forum reading, I managed to access the contents of a file and display them from within the Jar file. The problem is that if I were to put the file inside a folder then my program would no longer work even though it works when I run the class file. This is a problem because when I make games and other programs I like having different folders for organisation like "maps" and "spritesheets". I made an experimental program to route out the problem and here is the code for it:

        try {
              InputStream is = getClass().getResourceAsStream("folder\\test.txt");
              InputStreamReader isr = new InputStreamReader(is);
              BufferedReader br = new BufferedReader(isr);
              String line;
              while ((line = br.readLine()) != null)  {
                System.out.println(line);
              }
             br.close();
             isr.close();
             is.close();

       } catch (Exception ex) {}

I didn't do anything in the catch section because I had already used it to find the area with the problem. Here is my directory structure:

JarFileText
  classes
    com
      sayedhajaj
        folder
          test.txt
        JarFileText.class
        test.txt
   source
     com
       sayedhajaj
         JarFileText.java

When I try to access the copy of the text file that is not in the folder, everything works fine. However, if I try to access the copy in "folder", null is returned.

Upvotes: 0

Views: 111

Answers (1)

Sayed Hajaj
Sayed Hajaj

Reputation: 62

This is the solution:

        try {
              InputStream is = getClass().getResourceAsStream("folder/test.txt");
              InputStreamReader isr = new InputStreamReader(is);
              BufferedReader br = new BufferedReader(isr);
              String line;
              while ((line = br.readLine()) != null)  {
                System.out.println(line);
              }
             br.close();
             isr.close();
             is.close();

       } catch (Exception ex) {}

Upvotes: 2

Related Questions