1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
public static void main(){
try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(packageDataPath))) {
String prefixPath = "/Test/";
zipFileToPackage(zipOutputStream, prefixPath, new File(sourcePath), sourcePath);
} catch (Exception e) {
throw new RuntimeException("打包成果文件失败!", e);
}
}
private void zipFileToPackage(ZipOutputStream zipOutputStream, String prefixPath, File file, String rootFilePath) throws IOException {
System.out.println("打包数据 " + file.getAbsolutePath() + " 到 " + prefixPath);
rootFilePath = rootFilePath.replace("\\", "/").replace("//", "/");
String filePath = file.getAbsolutePath().replace("\\", "/").replace("//", "/");
String zipEntryPath = prefixPath + filePath.replace(rootFilePath, "");
zipEntryPath = zipEntryPath.replace("//", "/");
if (file.isFile()) {
zipOutputStream.putNextEntry(new ZipEntry(zipEntryPath));
zipOutputStream.write(FileUtils.readFileToByteArray(file));
zipOutputStream.closeEntry();
}
if (file.isDirectory()) {
zipOutputStream.putNextEntry(new ZipEntry(zipEntryPath + "/"));
zipOutputStream.closeEntry();
File[] files = file.listFiles();
for (File child : files) {
zipFileToPackage(zipOutputStream, prefixPath, child, rootFilePath);
}
}
}
|
Preview: