2008年5月27日 星期二

簡易的java compression and decompression

目前在做之前學長的Video Annotation tool多個model的整合...常常training出來的model感覺檔案都很大...(因為我只有把它tar起來XD)...有鑑於此,,所以寫了一個簡易的compression/decompression的程式..主要改自Simple String Compression Functions 不過為了符合我的需要,input/output都是一個file,,不過這個blog好像沒辦法上傳檔案..XD所以底下大概看一下吧XD

compression 的infile就是原先的tar起來的file, outfile就是compression放置的地方
decompression的動作就是相反.

  1. /**
  2. * the input is the file that we want to compression
  3. * the output is the compressed file
  4. * @param infile
  5. * @param outfile
  6. * @return
  7. * @throws IOException
  8. */
  9. static public void compression(String infile, String outfile)throws IOException{
  10. try{
  11. byte[] buffer = new byte[1024];
  12. int offset = -1;
  13. fin = new BufferedInputStream( new FileInputStream(infile));
  14. fout = new BufferedOutputStream ( new FileOutputStream(outfile));
  15. zout.putNextEntry(new ZipEntry("0"));
  16. while( (offset = fin.read(buffer)) != -1){
  17. zout.write(buffer, 0, offset);
  18. }
  19. zout.closeEntry();
  20. byte[] compressed = out.toByteArray();
  21. zout.close();
  22. fout.write(compressed);
  23. fout.close();
  24. }
  25. catch(IOException e){
  26. new IOException("simpleCompression.compression exception");
  27. }
  28. finally{
  29. if(fin != null){
  30. fin.close();
  31. }
  32. if(fout != null){
  33. fout.flush();
  34. fout.close();
  35. }
  36. }
  37. }
  38. /**
  39. * the input is the compressed file
  40. * the output is the original file
  41. * @param compressed
  42. * @return
  43. * @throws IOException
  44. */
  45. static public void decompression(String infile, String outfile)throws IOException{
  46. int read=0;
  47. byte[] buffer = new byte[1024];
  48. BufferedWriter fout = null;
  49. ZipInputStream zin = null;
  50. try{
  51. fin = new BufferedInputStream( new FileInputStream(infile));
  52. zin = new ZipInputStream(fin);
  53. ZipEntry entry = zin.getNextEntry();
  54. int offset = -1;
  55. while((offset = zin.read(buffer)) != -1) {
  56. out.write(buffer, 0, offset);
  57. }
  58. fout = new BufferedWriter(new FileWriter(outfile));
  59. fout.write(out.toString());
  60. }
  61. catch(IOException e){
  62. new IOException("simpleCompression.decompression exception");
  63. }
  64. finally{
  65. if(fin != null)
  66. fin.close();
  67. if(fout != null){
  68. fout.flush();
  69. fout.close();
  70. }
  71. if(out != null)
  72. out.close();
  73. if(zin != null)
  74. zin.close();
  75. }
  76. }