is it possible to get a File or URI object for a file inside an archive with Java? (zip or jar archive)
Thanks Hemeroc.
To read the file represented by a ZipEntry you can obtain an InputStream from the ZipFile like this: ZipEntry zipEntry = zipFile. getEntry("dir/subdir/file1.
Methods. getComment(): String – returns the zip file comment, or null if none. getEntry(String name): ZipEntry – returns the zip file entry for the specified name, or null if not found. getInputStream(ZipEntry entry) : InputStream – Returns an input stream for reading the contents of the specified zip file entry.
Java API provides extensive support to read Zip files, all classes related to zip file processing are located in the java. util. zip package. One of the most common tasks related to zip archive is to read a Zip file and display what entries it contains, and then extract them in a folder.
To unzip a zip file, we need to read the zip file with ZipInputStream and then read all the ZipEntry one by one. Then use FileOutputStream to write them to file system. We also need to create the output directory if it doesn't exists and any nested directories present in the zip file.
The jar:
protocol is a way to build a URI to a resource in a JAR archive:
jar:http://www.example.com/bar/baz.jar!/path/to/file
See the API docs for JarURLConnection: http://java.sun.com/javase/6/docs/api/java/net/JarURLConnection.html
Between the jar:
and !/
can be any URL, including a file:
URL.
public List<File> getFilesInJar(String jarName){
List<File> result = new ArrayList<File>();
File jarFile = new File(jarName);
JarInputStream jarFile = new JarInputStream(new FileInputStream(jarFile));
JarEntry jarEntry;
while ((jarEntry = jarFile.getNextJarEntry()) != null) {
result.add(inputStreamToFile(jarFile.getInputStream(jarEntry)));
}
return result;
}
for the inputStreamToFile method, google "java inputStream to file", although you might be happy with an InputStream object also, instead of a File object :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With