1

I'm trying to read a folder in a jar file, it works fine when it's not in jar format, however when i jar it, it returns a nullpointerexpcetion since it's not able to find the files nor the directory

So, here's the method i have....

public void preloadModelsTwoOLD() {
    String slash = System.getProperty("file.separator");
    File file = new File("."+ slash +"Patches" + slash+"Models"+slash);
    File[] fileArray = file.listFiles();
    for(int y = 0; y < fileArray.length; y++) {
        String s = fileArray[y].getName();
       if (s != "") {
        byte[] buffer = readFile("."+ slash +"Patches" + slash+"Models"+slash+""+s);
        Model.method460(buffer, Integer.parseInt(getFileNameWithoutExtension(s)));
        //System.out.println("Read model: " + s);
       }
    }
}

Basically this is in a java file inside the jar and the jar has this directory that has the files i need it to read

file.java is in main folder main folder/classes/patches/models but the class file reads from the classes folder so i have it like this ./patches/models/+i+.dat

any ideas as to why it's not reading it properly and how to go about fixing it so it'll work when in jar format if not both formats? any help is appreciated.

Travs
  • 83
  • 1
  • 2
  • 9
  • possible duplicate of [How do I list the files inside a JAR file?](http://stackoverflow.com/questions/1429172/how-do-i-list-the-files-inside-a-jar-file) – Snicolas Mar 25 '12 at 20:34

2 Answers2

1

Files in a JAR are treated as resources.

You need to use

InputStream fileStream = getClass().getResourceAsStream("dir1/dir2/file1")

and then use the InputStream APIs to read from it

Vijay Agrawal
  • 3,751
  • 2
  • 23
  • 25
  • how do i use it in this method though? – Travs Mar 25 '12 at 20:31
  • So you can use the classloader to get the list of resources in that 'package'. classloader.getResources() should give you the list. See snippets.dzone.com/posts/show/4831 for examples on usage – Vijay Agrawal Mar 25 '12 at 20:36
1

You should not use a file this way : the path is either absolute or relative to the directory you are executing java from.

Prefer to use

URL url = getClass().getResource( "<path relative to the dir containing the .class file of invoking class>" );
File file = new File( url.toURI() );

You also have this resource and the duplicate I added.

Snicolas
  • 37,840
  • 15
  • 114
  • 173
  • okay so now i have this InputStream fileStream = getClass().getResourceAsStream("."+ slash +"Patches" + slash+"Models"+slash); File[] fileArray = fileStream.listFiles(); however listFiles()'s isn't a valid method for resources, what would it be for resources? – Travs Mar 25 '12 at 20:23