public class ZipUtils {
public static void downloadFiles(String srcSource, String pin, String shmy, String url) {
HttpServletResponse response = HttpContextUtils.getHttpServletResponse();
String downloadName = "gateway.zip";
try {
OutputStream out = response.getOutputStream();
byte[] data = createZip(srcSource, pin, shmy, url);
response.reset();
response.setHeader("Content-Disposition", "attachment;fileName=" + downloadName);
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/octet-stream;charset=UTF-8");
IOUtils.write(data, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static byte[] createZip(String srcSource, String pin, String shmy, String url) throws Exception {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
File file = new File(srcSource);
compressZip(zip, file, "");
appendPropFile(zip, "/prop.properties", pin, shmy, url);
IOUtils.closeQuietly(zip);
return outputStream.toByteArray();
}
public static void compressZip(ZipOutputStream zip, File file, String dir) throws Exception {
if (file.isDirectory()) {
File[] files = file.listFiles();
zip.putNextEntry(new ZipEntry(dir + "/"));
dir = dir.length() == 0 ? "" : dir + "/";
for (int i = 0; i < files.length; i++) {
compressZip(zip, files[i], dir + files[i].getName());
}
} else {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
ZipEntry entry = new ZipEntry(dir);
zip.putNextEntry(entry);
zip.write(FileUtils.readFileToByteArray(file));
IOUtils.closeQuietly(bis);
zip.flush();
zip.closeEntry();
}
}
public static void appendPropFile(ZipOutputStream zip, String dir, String pin, String shmy, String url)
throws Exception {
String str = "[sys]\r\ncipher=" + shmy + "\r\nport=6888\r\nurl=" + url + "\r\npin=" + pin;
ZipEntry entry = new ZipEntry(dir);
zip.putNextEntry(entry);
zip.write(str.getBytes("UTF-8"));
zip.flush();
zip.closeEntry();
}
public static void main11(String[] args) throws IOException {
String path = "C:\\Users\\Administrator\\Desktop\\201904281023332820200407.zip";
InputStream in = new BufferedInputStream(new FileInputStream(path));
Charset gbk = Charset.forName("gbk");
ZipInputStream zin = new ZipInputStream(in,gbk);
ZipEntry ze;
while((ze = zin.getNextEntry()) != null){
if(ze.toString().endsWith("txt")){
BufferedReader br = new BufferedReader(
new InputStreamReader(zin));
String line;
while((line = br.readLine()) != null){
System.out.println(line.toString());
}
}
System.out.println();
}
zin.closeEntry();
in.close();
}
}