When doing a file operation, the general steps are as follows:
Read operation: To target file new an input stream-> read data-> manipulate data
Write: New to target file a output stream-> call write method write data
Understanding the Java compression technology should first understand the structure of the zip file, the following figure, a zip file contains multiple zipentry, called "entries."
The operation of the zip file is similar to the normal file operation, the only difference is that the zip file has a different data structure, and the zip file is a container containing multiple files. Therefore read and write to the zip file is the document in the container to read and write.
Read operations: New to target zip file a zip input stream-> for each entry, a new file input stream for the entry, read the entry data-> manipulate the data
Write: New to target zip file a zip output stream-> for each entry, a new file output stream for the entry, and then writes the data
Code for read operations:
@Test public
void Runzipinputstream () throws IOException {
//1. Create a Zip input stream
zipinputstream Zin = new Zipinputstream (New FileInputStream ("Iotest.zip"));
ZipEntry ze;
2. Processing entries one
by one while ((Ze = zin.getnextentry ())!= null) {
//test: Output Entry information
System.out.printf ("Entry information: Name%1$b, size%2$d, Compression time%3$d \ n ", Ze.getname (), Ze.getsize (), Ze.gettime ());
3. Operation file Content-output, processing
fileinputstream fin = new FileInputStream (Ze.getname ());
byte[] buffer = new byte[4096];
int Len;
while (len = fin.read (buffer))!=-1) {
System.out.print (new String (buffer, 0, Len);}}
}
Write operation code:
@Test public
void Runzipoutputstream () throws IOException {
//1. Create a Zip output stream
zipoutputstream Zos = new Zipoutputstream (New FileOutputStream ("Javaio.rar"));
2. Create and set the entry information
file F = new file ("Javaio.bmp");
ZipEntry ze = new ZipEntry (F.getname ());
Ze.setcomment ("Hello, Zip");
Ze.setsize (F.length ());
Ze.settime (F.lastmodified ());
3. Add entry to output stream
zos.putnextentry (ze);
4. Output
fileinputstream fin = new FileInputStream (f);
byte[] buffer = new byte[4096];
int Len;
while (len = fin.read (buffer))!=-1) {
zos.write (buffer, 0, Len);
}
Fin.close ();
5. Close Stream
zos.close ();
}
The above code is to operate on a single file, if you want to compress the entire directory, you need to traverse all the files in the directory.