ZipOutputStream
时间: 2023-10-22 22:15:38 浏览: 78
ZipOutputStream is a class in Java that allows for the creation of ZIP files. It is part of the java.util.zip package and extends the DeflaterOutputStream class. ZipOutputStream can be used to create a new ZIP file or add entries to an existing ZIP file.
To create a new ZIP file using ZipOutputStream, first create a new instance of the class and pass it an OutputStream object. Then, use the putNextEntry method to create a new entry in the ZIP file and write data to it using the write method. When finished adding entries to the ZIP file, use the closeEntry method to close the current entry and finalize its contents. Lastly, use the finish method to finish writing the ZIP file and close the ZipOutputStream.
Example code for creating a new ZIP file using ZipOutputStream:
```
import java.io.*;
import java.util.zip.*;
public class CreateZipFile {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("example.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
// create a new entry in the zip file
ZipEntry entry = new ZipEntry("file.txt");
zos.putNextEntry(entry);
// write data to the entry
String data = "This is some example data.";
zos.write(data.getBytes());
// close the current entry
zos.closeEntry();
// finish writing the zip file
zos.finish();
zos.close();
System.out.println("Zip file created successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文