在读取网络文件中的文件时有可能是gzip tar zip格式的压缩文件,通常要直接通过网络读取第三方的数据,下面记录了一下使用ZipInputStream 中ZipEntry中的txt文件
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost("https://
mobile/phone/download");
Map<String,String> poststr = new HashMap<String,String>();
poststr.put("param1", "1.0.2");
poststr.put("param2", "12345");
poststr.put("param3", "323f");
poststr.put("param4", "232323");
List<BasicNameValuePair> basicNameValuePairList = new ArrayList<BasicNameValuePair>();
for (Map.Entry<String, String> paramEntry : poststr.entrySet()) {
basicNameValuePairList.add(new BasicNameValuePair(paramEntry.getKey(), paramEntry.getValue()));
}
post.setEntity(new UrlEncodedFormEntity(basicNameValuePairList, "UTF-8"));
HttpRequestBase httpRequestBase = post;
HttpResponse response = httpClient.execute(httpRequestBase);
System.out.println(response.getStatusLine().getStatusCode());
String data = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println("=====================");
System.out.println(data);
int index = data.indexOf("aaa=111");
if (index < 0) {
System.out.println("failed");
return ;
}
String[] datas = data.split("=");
byte[] bytes = new BASE64Decoder().decodeBuffer(datas[3]);
byte[] data1 = null;
ByteArrayInputStream in;
ZipInputStream zip;
try {
in = new ByteArrayInputStream(bytes);
zip = new ZipInputStream(in);
while (zip.getNextEntry() != null) {
byte[] buf = new byte[1024];
int num = -1;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((num = zip.read(buf, 0, buf.length)) != -1) {
baos.write(buf, 0, num);
}
data1 = baos.toByteArray();
}
System.out.println(new String(data1));
} catch (IOException e) {
e.printStackTrace();
} finally {
zip.close();
in.close();
}
上面仅供参考,由于是读取第三方系统的数据,不方便将所有的代码都贴出来
如果是本地的zip文件可以使用ZipFIle 读取文件,然后通过ZipFile的getInputstream()去获取流解析
流如果是文本文件可以直接使用Apach commons-Io包中IOUtils.toString()读取文件内容。