3

Currently I use this solution to load resources:

URL url = MyClass.class.getClassLoader().getResource("documents/"+path);
if(url == null)
    throw new FileNotFoundException();

BufferedReader reader = new BufferedReader(
    new InputStreamReader(url.openStream()));

Sadly I can't control whether path is a file or a directory. Is there any way I can determine if the denoted path is a directory? I'm looking for a solution independent from where the resource is loaded (in other words: File.isFile won't work when loading resource from JAR).

f4lco
  • 3,588
  • 3
  • 25
  • 51

1 Answers1

0

I use this code to grab names of text files from a jar.

public String[] getFiles() throws IOException {
    ArrayList<String> list = new ArrayList<String>();
    List<JarEntry> ents = new ArrayList<JarEntry>();
    Enumeration<JarEntry> e = null;

    URL jarp = getLocation();
    if (jarp != null) {
        jar = jarp.getProtocol().equalsIgnoreCase("jar") ? jarp : new URL("jar:" + jarp.toString() + "!/");
        JarFile jarf = null;
        try {
            jarf = AccessController.doPrivileged(
                    new PrivilegedExceptionAction<JarFile>() {

                        @Override
                        public JarFile run() throws Exception {
                            JarURLConnection conn = (JarURLConnection) jar.openConnection();
                            conn.setUseCaches(false);
                            return conn.getJarFile();
                        }
                    });
        } catch (PrivilegedActionException ex) {
            Logger.getLogger(LicenseLoader.class.getName()).log(Level.SEVERE, null, ex);
        }
        e = jarf.entries();
        while (e.hasMoreElements()) {
            JarEntry je = e.nextElement();
            if (!je.isDirectory()) {
                ents.add(je);
            }
        }
        for (JarEntry ent : ents) {
            if ((ent.getName().startsWith(pathName)) && (ent.getName().endsWith(".txt"))) {
                String name = ent.getName().replace(pathName, "");
                list.add(name);
            }
        }
    }
    return list.toArray(new String[list.size()]);
}
Mitch Connor
  • 736
  • 10
  • 18