压缩包在内存中添加文件,并直接输出

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ApkUtil {

private static final Logger logger = LoggerFactory.getLogger(ApkUtil.class);
private static final byte[] sourceApkBytes = initializeSourceApk();

private ApkUtil(){}
private static byte[] initializeSourceApk() {
String sourceApkPath = ApkUtil.class.getResource("/app/ZHXS.apk").getPath();
byte[] tmpBytes = new byte[1024];
File apkFile = new File(sourceApkPath);
ByteArrayOutputStream apkOut = new ByteArrayOutputStream();
FileInputStream apkFis = null;
try {
apkFis = new FileInputStream(apkFile);
int b = 0;
while ((b = apkFis.read(tmpBytes)) != -1) {
apkOut.write(tmpBytes, 0, b);
}
return apkOut.toByteArray();
} catch (Exception e) {
logger.error(e.getMessage() ,e);
} finally {
closeInputStream(apkFis);
closeOutputStream(apkOut);
}
return null;
}

private static void closeOutputStream(OutputStream outputStream) {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}

private static void closeInputStream(InputStream inputStream) {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}

public static byte[] addFilesToExistingZip(String fileName) throws IOException {

ByteArrayOutputStream finalByteArrayOutputStream = new ByteArrayOutputStream();
ZipOutputStream zipOutputStrem = new ZipOutputStream(finalByteArrayOutputStream);

ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(sourceApkBytes));
ZipEntry entry = zipInputStream.getNextEntry();
byte[] buf = new byte[1024];
while (entry != null) {
String name = entry.getName();
zipOutputStrem.putNextEntry(new ZipEntry(name));
int len;
while ((len = zipInputStream.read(buf)) > 0) {
zipOutputStrem.write(buf, 0, len);
}
entry = zipInputStream.getNextEntry();
}
closeInputStream(zipInputStream);

if (StringUtils.isNotBlank(fileName)) {
zipOutputStrem.putNextEntry(new ZipEntry("META-INF/" + fileName));
}
zipOutputStrem.closeEntry();
closeOutputStream(zipOutputStrem);
return finalByteArrayOutputStream.toByteArray();
}

public static void downloadApk(String fileName, HttpServletResponse response) {
ServletOutputStream output = null;
try {
output = response.getOutputStream();
byte[] bytes = null;
if (StringUtils.isNotBlank(fileName)) {
bytes = addFilesToExistingZip(fileName);
} else {
bytes = sourceApkBytes;
}
output.write(bytes);
} catch (IOException e) {
logger.error("Failed to download" + fileName + "apk");
} finally {
closeOutputStream(output);
}
}

public static void main(String[] args) {
try {
byte[] bytes = addFilesToExistingZip("zhxs_2699_"+URLEncoder.encode("测试", "utf-8"));
String targetDir = ApkUtil.class.getResource("/app/").getPath();
// 输出
FileOutputStream outt = new FileOutputStream(new File(targetDir + "zhxs_2699.apk"));
outt.write(bytes);
outt.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
示例代码: ```java public class FileZipUtil { public static void zipFiles(List<File> files, String zipFileName, HttpServletResponse response) throws Exception { // 创建压缩包输出流 ByteArrayOutputStream bos = new ByteArrayOutputStream(); // 创建ZipOutputStream对象,将压缩包输出流作为参数传入 ZipOutputStream zos = new ZipOutputStream(bos); // 设置压缩级别 zos.setLevel(Deflater.DEFAULT_COMPRESSION); // 遍历文件列表,将每个文件压缩并写入压缩包输出 for (File file : files) { // 获取文件输入流 FileInputStream fis = new FileInputStream(file); // 创建ZipEntry对象,表示压缩包的一个文件 ZipEntry entry = new ZipEntry(file.getName()); // 将ZipEntry对象添加到ZipOutputStream对象 zos.putNextEntry(entry); // 将文件内容写入ZipOutputStream对象 byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1) { zos.write(buffer, 0, len); } // 关闭ZipEntry对象 zos.closeEntry(); // 关闭文件输入流 fis.close(); } // 关闭ZipOutputStream对象 zos.close(); // 将压缩包输出的内容转换成byte数组 byte[] bytes = bos.toByteArray(); // 创建文件输出流 OutputStream os = response.getOutputStream(); // 设置响应头信息,指定下载文件名和文件类型 response.setHeader("Content-Disposition", "attachment;filename=" + zipFileName + ".zip"); response.setContentType("application/octet-stream;charset=UTF-8"); // 获取byte数组长度 int len = bytes.length; // 设置缓冲区大小 int bufferSize = 1024; // 计算需要分多少次传输 int times = len % bufferSize == 0 ? len / bufferSize : len / bufferSize + 1; // 设置进度条初始值为0 int process = 0; // 循环写入文件内容到响应输出,并更新进度条 for (int i = 0; i < times; i++) { int start = i * bufferSize; int end = Math.min(len, (i + 1) * bufferSize); os.write(bytes, start, end - start); os.flush(); // 更新进度条 process = (int) (((double) (i + 1)) / times * 100); // 将进度条信息写入响应输出 os.write(("data:" + process + "%\n\n").getBytes(StandardCharsets.UTF_8)); os.flush(); } // 关闭输出流 os.close(); } } ``` 使用示例: ```java List<File> files = new ArrayList<>(); files.add(new File("file1.txt")); files.add(new File("file2.txt")); files.add(new File("file3.txt")); FileZipUtil.zipFiles(files, "test", response); ``` 其,`files`为要压缩文件列表,`zipFileName`为生成的压缩包文件名(不包括后缀名),`response`为响应对象。在下载压缩包时,会显示一个进度条,以便用户了解下载进度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值