`

读写zip文件

 
阅读更多

import java.io.*;
import java.util.zip.*;
/*
 * Creates a ZIP file to be read by Winzip or Winrar
 */
public class WriteZip {

 public static void main(String[] args) {
  
  // lets put 2 files
  String[] filename = {"file1.dat", "file2.dat"};
  // create a line of text for the files
        byte[] buffer = new byte[27];        // the alphabet + <line feed?
        byte letter = 'a';
        for(int i = 0; i < 26; ++i)
         buffer[i] = letter++;
        buffer[26] = '\n';   // and an end of line
       
        try {
      // Create the ZIP file
      String outFilename = "myzip.zip";
      ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));

      // Compress two files
      for (int i=0; i<filename.length; i++) {
          // Add ZIP entry to output stream.
          out.putNextEntry(new ZipEntry(filename[i]));

          // Transfer 10 lines into the file
          for(int j = 0; j < 10; ++j)
              out.write(buffer);

          // Close the file
          out.closeEntry();
      }

      // Close the ZIP file
      out.close();
  } catch (IOException e) {
   System.out.println("Problem writing ZIP file: " + e);
  }

 }
}

 

import java.io.*;
import java.util.zip.*;

public class ReadZip {

 public static void main(String[] args) {
  try {
   // Open the ZIP file
   String inFilename = "myzip.zip";
   ZipInputStream in = new ZipInputStream(new FileInputStream(inFilename));

   // While we have other entry
   ZipEntry entry = in.getNextEntry();
   while(entry != null){
    System.out.println("Reading: " + entry.getName());
    // Transfer bytes from the ZIP file to the output file
    // OK I know that my file contains 10 * 27 bytes the reading might
    // be more versatile and test if there is more bytes in the file
    byte[] buf = new byte[1024];
    
    int len = in.read(buf);
             String theFile = new String(buf, 0, len);
    System.out.println(theFile);

    entry = in.getNextEntry();
   } // end while
   // Close the ZIP file
   in.close();
  } catch (IOException e) {
   System.out.println("Probel reading back the ZIP file: " + e);
  }

 }

参考:http://www.dreamincode.net/forums/topic/244086-write-and-read-zip-file-from-java/

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics