【发布时间】:2013-11-28 12:02:30
【问题描述】:
我正在从 X 站点下载所有 gz 格式的文件。将所有文件下载到临时文件夹后,当我精确到 0KB 时..请帮助我解决代码 cmets..代码中的任何更改
URL site = new URL (sb.toString());
URLConnection uc = site.openConnection();
uc.setRequestProperty("Accept-Encoding", "gzip");//Here the change
java.io.BufferedInputStream in = new BufferedInputStream(uc.getInputStream());
//ZipInputStream gzin = new ZipInputStream(in);
GZIPInputStream gzin = new GZIPInputStream(in);
fileName = fileName.substring(fileName.lastIndexOf("/")+1);
File destFile = new File("D:\\source\\"+fileName);
java.io.FileOutputStream fos = new FileOutputStream(destFile);
GZIPOutputStream gz = new GZIPOutputStream(fos);
byte data[] = new byte[65536];
int gsize = 0;
while((gsize = gzin.read(data)) != -1)
{
gz.write(data, 0, gsize);
}
【问题讨论】:
-
你是否关闭了你的 Fileoutputstream,即 fos ?
-
您正在下载的文件已经被抓取?然后你不需要使用压缩流。更重要的是,完成后关闭输入流和输出流是非常必要的,否则它们不会刷新。此外,压缩流最后需要做一些工作来完成文件。如果您使用的是 java 7,请使用 try-with-resources。
-
进一步,
String获取文件名的操作是一个很大的禁忌。如果最后一个/被转义了怎么办?使用File对象并调用适当的方法 -File.getName()。
标签: java gzipinputstream gzipoutputstream