- 2 minutes read

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"); zipStream.putNextEntry(zipEntry); byte[] buffer = new byte[8192]; /**** beginning of the business logic ******************************/ do { int bytesRead = sourceFile.read(buffer); if (bytesRead <= 0) break; zipStream.write(buffer, 0, bytesRead); System.out.println(bytesRead); } while (true); /**** end of the business logic ******************************/ zipStream.closeEntry(); } catch (FileNotFoundException e) { System.out.println("The file does not exist."); } catch (IOException e) { System.out.println("An IO error occured." + e); e.printStackTrace(); } finally { if (null != zipStream) { try { zipStream.close(); } catch (IOException e) { System.out.println("An IO error occured when closing the zip stream." + e); } } if (null != zippedFile) { try { zippedFile.close(); } catch (IOException e) { System.out.println("An IO error occured when closing the zipped file." + e); } } if (null != sourceFile) try { sourceFile.close(); } 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.


Comments