Accueil > Java > Get list of sub packages

Get list of sub packages

28/01/2009

public static Package[] getSubPackages(Package pckg) throws IOException, ClassNotFoundException {
    // Translate the package name into an absolute path
    String name = "/" + pckg.getName().replace('.','/');

    // Get a File object for the package
    URL url = Launcher.class.getResource(name);
    File directory = new File(url.getFile());

    if (directory.exists()) {
        // Get the list of the files contained in the package
        File[] files = directory.listFiles();
        ArrayList pckgs = new ArrayList();
        for (int i=0; i<files.length;++i) {

            // we are only interested in .class files
            if (files[i].isDirectory()) {
                // removes the .class extension
                pckgs.add(Package.getPackage(pckg.getName()+"."+files[i].getName()));
            }
        }
        Package[] packages = new Package[pckgs.size()];
        for (int i=0; i<pckgs.size();++i) packages[i] = (Package)pckgs.get(i);
        return packages;
    } else {
        throw new IOException("Invalid directory: "+url);
    }
}    

Java

Les commentaires sont fermés.