您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中处理ZIP文件格式的转换,可以使用Java内置的java.util.zip
包
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class ReadZIPFile {
public static void main(String[] args) {
String zipFilePath = "path/to/your/zipfile.zip";
try (FileInputStream fis = new FileInputStream(zipFilePath);
ZipInputStream zis = new ZipInputStream(fis)) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
System.out.println("Entry: " + entry.getName());
// 读取文件内容,如果需要的话
// byte[] buffer = new byte[entry.getSize()];
// zis.read(buffer);
zis.closeEntry();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class CreateZIPFile {
public static void main(String[] args) {
String zipFilePath = "path/to/your/outputfile.zip";
File[] filesToAdd = new File[]{
new File("path/to/your/file1.txt"),
new File("path/to/your/file2.txt")
};
try (FileOutputStream fos = new FileOutputStream(zipFilePath);
ZipOutputStream zos = new ZipOutputStream(fos)) {
for (File file : filesToAdd) {
ZipEntry entry = new ZipEntry(file.getName());
zos.putNextEntry(entry);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = file.read(buffer)) != -1) {
zos.write(buffer, 0, bytesRead);
}
zos.closeEntry();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class ExtractZIPFile {
public static void main(String[] args) {
String zipFilePath = "path/to/your/zipfile.zip";
String outputFolderPath = "path/to/your/outputfolder";
File outputFolder = new File(outputFolderPath);
if (!outputFolder.exists()) {
outputFolder.mkdirs();
}
try (FileInputStream fis = new FileInputStream(zipFilePath);
ZipInputStream zis = new ZipInputStream(fis)) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
File outputFile = new File(outputFolderPath, entry.getName());
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().mkdirs();
}
if (entry.isDirectory()) {
outputFile.mkdirs();
} else {
try (FileOutputStream fos = new FileOutputStream(outputFile)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = zis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
}
}
zis.closeEntry();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
这些示例展示了如何在Java中读取、创建和提取ZIP文件。你可以根据需要修改这些示例以满足你的具体需求。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。