[英]Extract contents of Zip file downloaded using a HTTP GET request
我必須從 rest 調用下載一個 Zip 文件並提取其內容(一些 PDF 文件和一個 PNG 文件)。
我正在使用 Java Spring。
怎么辦?
可以使用 Spring 的 RestTemplate 下載文件
RestTemplate templ = new RestTemplate();
byte[] downloadedBytes = templ.getForObject(url, byte[].class);
使用標准 java 或第三方庫提取內容。
示例實用程序,改編自此處: http : //www.codejava.net/java-se/file-io/programmatically-extract-a-zip-file-using-java
package com.test;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class ZipHelper {
private static final int BUFFER_SIZE = 4096;
public static void unzip(byte[] data, String dirName) throws IOException {
File destDir = new File(dirName);
if (!destDir.exists()) {
destDir.mkdir();
}
ZipInputStream zipIn = new ZipInputStream(new ByteArrayInputStream(data));
ZipEntry entry = zipIn.getNextEntry();
while (entry != null) {
String filePath = dirName + File.separator + entry.getName();
if (!entry.isDirectory()) {
// if the entry is a file, extracts it
extractFile(zipIn, filePath);
} else {
// if the entry is a directory, make the directory
File dir = new File(filePath);
dir.mkdir();
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
zipIn.close();
}
private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] bytesIn = new byte[BUFFER_SIZE];
int read = 0;
while ((read = zipIn.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
bos.close();
}
}
然后你像這樣使用這個實用程序:
ZipHelper.unzip(downloadedBytes, "/path/to/directory");
請求體應該是這樣的:
@RequestMapping(value = "/push/{id}", method = RequestMethod.POST, consumes = MediaType.APPLICATION_OCTET_STREAM_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public String pushTransactions(@PathVariable("id") String id, @RequestBody byte[] str) throws MessagingException, JsonParseException, JsonMappingException, IOException {
在控制器中,你可以這樣做:
GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(str));
ByteArrayOutputStream out = new ByteArrayOutputStream();
int len;
while ((len = gis.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
gis.close();
out.close();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.