Zipping a file (Java 6 style)

Zipping a file in Java is a rather trivial task you can find in many tutorials. However, I’d like to use it in a subsequent article, so I publish it anyways. By the way, it is another example of (almost) correct resource handling before Java 7.

To read a file and write a compressed version of it, you can copy the following code:

   public void zipFile(String p_inputFileName) {
      FileInputStream sourceFile = null;
      FileOutputStream zippedFile = null;
      ZipOutputStream zipStream = null;
      try {
         sourceFile = new FileInputStream(p_inputFileName);

         zippedFile = new FileOutputStream(p_inputFileName + ".zip");

         zipStream = new ZipOutputStream(zippedFile);
         ZipEntry zipEntry = new ZipEntry("uncompressed.txt");

         byte[] buffer = new byte[8192];
         /**** beginning of the business logic ******************************/
         do {
            int bytesRead = sourceFile.read(buffer);
            if (bytesRead <= 0)
            zipStream.write(buffer, 0, bytesRead);

         } while (true);
         /**** end of the business logic ******************************/
      } catch (FileNotFoundException e) {
         System.out.println("The file does not exist.");
      } catch (IOException e) {
         System.out.println("An IO error occured." + e);
      } finally {
         if (null != zipStream) {
            try {
            } catch (IOException e) {
               System.out.println("An IO error occured when closing the zip stream." + e);
         if (null != zippedFile) {
            try {
            } catch (IOException e) {
               System.out.println("An IO error occured when closing the zipped file." + e);
         if (null != sourceFile)
            try {
            } catch (IOException e) {
               System.out.println("An IO error occured when closing the buffer." + e);

As in the file reading example, most lines are simple boiler plate code. The business logic is limited to the seven lines between the asterics. This is why I believe closure are tremendously useful.

If you see any possibility to improve the code, feel free to leave a comment.

Leave a Reply

Your email address will not be published.