Big Data/Analytics Zone is brought to you in partnership with:
DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Find Files In Zip, Jar, War, Ear And Nested Archives

05.31.2005
| 24554 views |
  • submit to reddit
        The following java class takes two arguments; a directory name and a regular expression.  The directory is searched for files matching the regexp.  Zip files (and zip-alikes) are also searched including nested zips.

import java.io.*;
import java.util.*;
import java.util.zip.*;

public class Finder {
	public static void main(String[] args) throws Exception {
		String path = args[0];
		final String expr = args[1];

		List l = new ArrayList();
		findFile(new File(path), new P() {
			public boolean accept(String t) {
				return t.matches(expr) || isZip(t);
			}
		}, l);

		List r = new ArrayList();
		for (Iterator it = l.iterator(); it.hasNext();) {
			File f = (File) it.next();
			String fn = f + "";
			if (fn.matches(expr)) r.add(fn);
			if (isZip(f.getName())) {
				findZip(fn, new FileInputStream(f), new P() {
					public boolean accept(String t) {
						return t.matches(expr);
					}
				}, r);
			}
		}

		for (Iterator it = r.iterator(); it.hasNext();) {
			System.out.println(it.next());
		}
	}

	static void findFile(File f, P p, List r) {
		if (f.isDirectory()) {
			File[] files = f.listFiles();
			for (int i = 0; i < files.length; i++) findFile(files[i], p, r);
		} else if (p.accept(f + "")) {
			r.add(f);
		}
	}

	static void findZip(String f, InputStream in, P p, List r) throws IOException {
		ZipInputStream zin = new ZipInputStream(in);

		ZipEntry en;
		while ((en = zin.getNextEntry()) != null) {
			if (p.accept(en.getName())) r.add(f + "!" + en);
			if (isZip(en.getName())) findZip(f + "!" + en, zin, p, r);
		}
	}

	static String[] ZIP_EXTENSIONS = { ".zip", ".jar", ".war", ".ear" };

	static boolean isZip(String t) {
		for (int i = 0; i < ZIP_EXTENSIONS.length; i++) {
			if (t.endsWith(ZIP_EXTENSIONS[i])) {
				return true;
			}
		}
		return false;
	}

	static interface P {
		public boolean accept(String t);
	}
}


<em>Files are not properly closed!  Don't use this class in a long running application or properly close all streams.</em>