【发布时间】:2019-11-27 19:51:22
【问题描述】:
我是使用流的新手。我正在尝试在我的应用程序中使用 httpClient 下载 zipfile。当我下载 zip 文件时,我从客户端获得了成功的响应。我正在尝试生成 zipfile使用输入流在我的本地文件夹中。我能够生成 zip 文件,但没有内容。有人可以在这里帮助我。下面是我的代码sn-p。
String url = CONTANTS.SERVER_LOCATION+"Download/Test/"+ "sudhakar_test.zip";
HttpGet getRequest = new HttpGet(url);
CloseableHttpClient httpClient =HttpClientBuilder.create().build();
try (
CloseableHttpResponse response = httpClient.execute(getRequest);
InputStream fileInput = response.getEntity().getContent();
ZipInputStream zipInput = new ZipInputStream (fileInput);
FileOutputStream output = new FileOutputStream(new File(fileLocation
+"/SudhakarZIP_Test.zip"));
)
{
if (response.getStatusLine().getStatusCode() == 200)
{
byte[] buffer = new byte[1024];
int length;
while((length = zipInput.read(buffer,0,buffer.length)) >0)
{
output.write(buffer,0,length);
}
}
【问题讨论】:
-
如果省略
ZipInputStream并直接使用内容的InputStream会怎样?那你有什么收获吗?我认为您至少需要从 ZIP 流中调用getNextEntry以获取任何有意义的内容,因为ZipInputStream正在读取整个存档,而不是单个文件。这是一个答案,不是吗?我已经把它写成了一个。 -
提示:如果您的唯一目的是将流保存到文件,则不需要
ZipInputStream。你应该省略zipInput,直接使用fileInput。 -
Marteen,下面两行代码已经将 zip 文件作为输入流下载,但我的目标是使用下载的内容在本地生成 zip 文件。 CloseableHttpResponse 响应 = httpClient.execute(getRequest); InputStream fileInput = response.getEntity().getContent();
-
首先生成 zip 文件和从远程服务器下载 zip 文件是完全不同的事情。 Marteen 也应该对您的问题投反对票,因为您没有阅读网络上的任何内容并且您的问题不清楚。
标签: java webservice-client fileinputstream fileoutputstream zipinputstream