http://www.dreaminco...gopid__1415329&
This is how to read/write a .zip file in Java
We will create a ZIP file myzip.zip into which we will put file1.dat and file2.dat
containing the alphabet (a-z) witten 10 times
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);
}
}
}
And now the code to read it back. It prints the name of the file and their content
I knew the size of the file so I cheated and just create a buffer of bytes large enough to read the whole file. A real program should check the the number of bytes returned by the InputStream, but I kept it simple for shortening the code.
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);
}
}
}






MultiQuote




|