0

So here is my problem: I have here a program that gets all files and folders in a certian directory:

import java.io.File;
import java.util.ArrayList;

public class getFilesAndFolders {

private String[] filesAndFolders = {};
private ArrayList<String> filesAndFolders2 = new ArrayList<String>(filesAndFolders.length +1);

public String[] get(String location){

    File files = new File(location);
    File[] fList = files.listFiles();

    for(File fileLoop : fList){
        if(files.isDirectory()){
            String placeHolder = fileLoop.getPath();
            filesAndFolders2.add(placeHolder);
            initialise();
        }else if(files.isFile()){
            String placeHolder = fileLoop.getPath();
            filesAndFolders2.add(placeHolder);
            initialise();
        }
    }

    return filesAndFolders;
}

private void initialise() {

    filesAndFolders = filesAndFolders2.toArray(new String[filesAndFolders2.size()]);
    filesAndFolders2 = new ArrayList<String>(filesAndFolders.length +1);

}

}

I call it with this: sample.get("sample//samples");

And it returns a nullPointerException at line 16. (The for loop)

Whereas when I type this:

private static Image n1 = new Image("sample//sample2//sample3.png");

The file would be found and the application would load fine. How can I make it so that this program returns something?

Ps: I got to to work before: But it was with a file outside the Jar file

Edit: I want to return the file list back as a String[]. Also, I don't want the computer to know beforehand what files exist there. (EG: If a files name is changed, the computer will still find it)

Icedude_907
  • 172
  • 3
  • 11

1 Answers1

0

If I'm reading your question properly, you want a list of entries in a jar file, without knowing in advance what's in the jar file.

To get the the list of entries in a jar file, you can use the java.util.jar.JarFile and java.util.jar.JarEntry classes:

String jarFileName = ...
JarFile jar = new JarFile( jarFileName );
Enumeration<JarEntry> entries = jar.entries();
while ( entries.hasMoreElements() )
{
    JarEntry entry = entries.nextElement();
    String entryName = entry.getName();
    // do something with the entryName String
    ...

    // get an InputStream for the entry
    InputStream is = jar.getInputStream( entry );
    ...
}
Andrew Henle
  • 32,625
  • 3
  • 24
  • 56