您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中处理ZIP文件格式,您可以使用java.util.zip
包中的类
import java.io.*;
import java.util.zip.*;
public class ZipExample {
public static void main(String[] args) {
String zipFileName = "example.zip";
String fileToZip = "example.txt";
try {
FileOutputStream fos = new FileOutputStream(zipFileName);
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze = new ZipEntry(fileToZip);
zos.putNextEntry(ze);
FileInputStream fis = new FileInputStream(fileToZip);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
zos.close();
fis.close();
fos.close();
System.out.println("File added to ZIP archive.");
} catch (IOException e) {
System.out.println("Error occurred while creating ZIP archive.");
e.printStackTrace();
}
}
}
import java.io.*;
import java.util.zip.*;
public class UnzipExample {
public static void main(String[] args) {
String zipFileName = "example.zip";
String destDirectory = "extracted/";
File destDir = new File(destDirectory);
if (!destDir.exists()) {
destDir.mkdir();
}
try {
FileInputStream fis = new FileInputStream(zipFileName);
ZipInputStream zis = new ZipInputStream(fis);
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String fileName = destDirectory + ze.getName();
if (!ze.isDirectory()) {
extractFile(zis, fileName);
} else {
File dir = new File(fileName);
dir.mkdirs();
}
zis.closeEntry();
ze = zis.getNextEntry();
}
zis.close();
fis.close();
System.out.println("Files extracted from ZIP archive.");
} catch (IOException e) {
System.out.println("Error occurred while extracting files from ZIP archive.");
e.printStackTrace();
}
}
private static void extractFile(ZipInputStream zis, String fileName) throws IOException {
FileOutputStream fos = new FileOutputStream(fileName);
byte[] buffer = new byte[1024];
int length;
while ((length = zis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
fos.close();
}
}
这两个示例分别演示了如何创建一个包含单个文件的ZIP文件以及如何从ZIP文件中提取所有文件。您可以根据需要修改这些示例以满足您的需求。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。