您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,可以使用java.util.zip
包中的类来实现Zip文件的压缩和解压缩
import java.io.*;
import java.util.zip.*;
public class ZipExample {
public static void main(String[] args) {
String zipFileName = "example.zip";
String[] filesToZip = {"file1.txt", "file2.txt", "file3.txt"};
try {
createZipFile(zipFileName, filesToZip);
System.out.println("文件压缩成功!");
} catch (IOException e) {
System.out.println("文件压缩失败!");
e.printStackTrace();
}
}
public static void createZipFile(String zipFileName, String[] filesToZip) throws IOException {
FileOutputStream fos = new FileOutputStream(zipFileName);
ZipOutputStream zos = new ZipOutputStream(fos);
for (String fileName : filesToZip) {
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(file.getName());
zos.putNextEntry(zipEntry);
byte[] bytesIn = new byte[4096];
int read = 0;
while ((read = fis.read(bytesIn)) != -1) {
zos.write(bytesIn, 0, read);
}
zos.closeEntry();
fis.close();
}
zos.close();
fos.close();
}
}
public class UnzipExample {
public static void main(String[] args) {
String zipFileName = "example.zip";
String destDirectory = "output";
try {
unzipFile(zipFileName, destDirectory);
System.out.println("文件解压缩成功!");
} catch (IOException e) {
System.out.println("文件解压缩失败!");
e.printStackTrace();
}
}
public static void unzipFile(String zipFileName, String destDirectory) throws IOException {
File destDir = new File(destDirectory);
if (!destDir.exists()) {
destDir.mkdir();
}
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFileName));
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
String filePath = destDirectory + File.separator + zipEntry.getName();
if (!zipEntry.isDirectory()) {
extractFile(zis, filePath);
} else {
File dir = new File(filePath);
dir.mkdirs();
}
zis.closeEntry();
zipEntry = zis.getNextEntry();
}
zis.close();
}
public static void extractFile(ZipInputStream zis, String filePath) throws IOException {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] bytesIn = new byte[4096];
int read = 0;
while ((read = zis.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
bos.close();
}
}
这些示例展示了如何使用Java的java.util.zip
包来压缩和解压缩文件。请确保将示例中的文件名更改为实际的文件名。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。