我有一个分段文件上传请求。该文件是 zip 文件 - .zip 格式。 我如何解压这个文件? 我需要用每个条目的文件路径和文件内容填充 HashMap 。
HashMap<filepath, filecontent>
我到目前为止的代码:
FileInputStream fis = new FileInputStream(zipName);
ZipInputStream zis = new ZipInputStream(
new BufferedInputStream(fis));
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
int size;
byte[] buffer = new byte[2048];
FileOutputStream fos =
new FileOutputStream(entry.getName());
BufferedOutputStream bos =
new BufferedOutputStream(fos, buffer.length);
while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
bos.write(buffer, 0, size);
}
bos.flush();
bos.close();
}
zis.close();
fis.close();
}
最佳答案
不要使用 FileOutputStream,而是使用 ByteArrayOutputStream 来捕获输出。然后,在 BAOS 上执行“close”操作之前,使用“toByteArray()”方法获取字节数组形式的内容(或者使用“toString()”)。因此,您的代码应如下所示:
public static HashMap<String, byte[]> test(String zipName) throws Exception {
HashMap<String, byte[]> returnValue = new HashMap<>();
FileInputStream fis = new FileInputStream(zipName);
ZipInputStream zis = new ZipInputStream(
new BufferedInputStream(fis));
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
int size;
byte[] buffer = new byte[2048];
ByteArrayOutputStream baos =
new ByteArrayOutputStream();
BufferedOutputStream bos =
new BufferedOutputStream(baos, buffer.length);
while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
bos.write(buffer, 0, size);
}
bos.flush();
bos.close();
returnValue.put(entry.getName(),baos.toByteArray());
}
zis.close();
fis.close();
return returnValue;
}
关于java - .zip 文件上传 Spring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38488053/