May 26

Java provides the ZipInputStream class for reading from a zip file. Heres a general example of its usage

File file = new File("my.zip");
ZipInputStream zin = new ZipInputStream(new FileInputStream(file));
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
   String filename = ze.getName();
   if (!ze.isDirectory()) {
        // Read file contents from 'zin'
        // For example you could read from zin and write it to a FileOutputStream
        // http://helpdesk.objects.com.au/java/how-do-i-copy-one-stream-to-another-using-java
   }
   zin.closeEntry();
}
zin.close();

The same can be used to read the contents of a jar file.

written by objects \\ tags: , , , , ,

Oct 15

We often want to quickly identify the type of a file. The following two libraries help us achieve that goal.

jMimeMagic

jMimeMagic is a Java library for determining the MIME type of files or streams.

Mime Type Detection Utility

Enable Java programs to detect MIME types based on file extensions, magic data and content sniffing. Supports detection from java.io.File, java.io.InputStream, java.net.URL and byte arrays.

written by objects \\ tags: , , ,

Jun 11

Many developers use the toURL() method of the File class to convert a File to a URL. This method however does not handle correctly escaping characters that are illegal in URL’s (such as spaces) and has been deprecated.

To convert a File to a URL you should instead first use the toURI() method to convert the file path to a URI. The URI class has a toURL() method that can then be used to convert the URI to a URL.

File file = new File(path);
URI uri = file.toURI();
URL url = uri.toURL();

// or alternatively in one line

URL url = file.toURI().toURL();

written by objects \\ tags: , , ,