Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a File or URI object for a file inside an archive with Java?

is it possible to get a File or URI object for a file inside an archive with Java? (zip or jar archive)

Thanks Hemeroc.

like image 625
Hemeroc Avatar asked Jan 12 '10 14:01

Hemeroc


People also ask

How do I get files from ZipEntry?

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.

How can I read the content of a zip file without unzipping it in Java?

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.

Can Java read ZIP files?

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.

How do I open a zip file with Java?

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.


2 Answers

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.

like image 121
ZoogieZork Avatar answered Oct 07 '22 08:10

ZoogieZork


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 :)

like image 29
Fortega Avatar answered Oct 07 '22 08:10

Fortega