简体   繁体   中英

Loading all files from a folder in a jar file

How can i load all files from a folder in a jar file?

Untill now i was loading files from a folder like this File[] files = new File("res/Models/" + dir).listFiles(); but it doesnt in a fat jar file (i get a NullPointerException ).

Note: The class that should load files and the files i want to load are in the same jar file. The line i wrote up there works when i run my program in eclipse, but when i expoort a jar file i get a NullPointerException for that line

A jar file is a zip file, so you can read its contents using a ZipInputStream like this:

  ZipFile zipFile = new ZipFile(file);
  ZipInputStream stream = new ZipInputStream(new BufferedInputStream(new FileInputStream(file)));
  ZipEntry entry = null;
  List<String> filePaths = new ArrayList<String>();
  while ((entry = stream.getNextEntry()) != null) {
    // this will get you the contents of the file
    InputStream inputStream = zipFile.getInputStream(entry);
    // this add the file path to the list
    filePaths.add(entry.getName());
  }

You can also do the follo

Let's look at how a File object works.

First, say we have the following code in a file named FileTest.java:

public class FileTest {
    public static void main() {
        File[] files = new File("temp").listFiles();

        for (File f : files) System.out.println(f.getName());
    }
}

When we compile this, javac creates a file named FileTest.class. (Even Eclipse will do this; it just places the .class files in a separate folder from the .java files.) Now when we run this program, it will look for a folder named "temp" located in the same folder as the FileTest.class file.

Now suppose that we create a JAR file named filetest.jar and add FileTest.class to it. Now if we run the program from the JAR file, it will look for a folder named "temp" located in the same folder as the filetest.jar file. In other words, File only looks for files and folders in the file system on your hard drive. It knows absolutely nothing about the contents of any files, including filetest.jar .

In order to read the contents of a JAR file, you must find a different solution. To start, you need to understand that inside a JAR file there is no such thing as "files" and "folders". A JAR file is simply a ZIP file with a few extra features. With the information you have given here so far, I believe that to solve your problem you will need to use java.util.zip.ZipFile . I suggest you start by googling for a tutorial or browing the API doc which I have linked here.

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