首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用java写程序下载.gz文件?

用java写程序下载.gz文件?
EN

Stack Overflow用户
提问于 2011-06-09 23:19:59
回答 2查看 3.4K关注 0票数 3

我一直在试着用java写一个程序,它可以帮我从一个在线的ftp服务器上下载一些.gz文件。这是我一直在使用的:

代码语言:javascript
运行
复制
public static void main(String[] args) throws IOException {
    URL url = new URL("ftp://ftp.ncbi.nih.gov/pub/geo/DATA/SOFT/by_series/GSE10/");
    URLConnection con = url.openConnection();
    BufferedInputStream in = new BufferedInputStream(con.getInputStream());
    FileOutputStream out = new FileOutputStream("GSE10_family.soft.gz");

    int i = 0;
    byte[] bytesIn = new byte[3000000];
    while ((i = in.read(bytesIn)) >= 0) {
        out.write(bytesIn, 0, i);
    }
    out.close();
    in.close();

}

程序可以正常运行并下载文件。但是,当我尝试解压缩.gz文件时,它会解压缩为.cpgz文件,这会导致.cpgz到.gz的无限循环,以此类推。

当我手动下载这个文件时,它会解压,一切都很好,所以我知道这不是文件的问题。

如有任何建议,我们将不胜感激!非常感谢!

EN

Stack Overflow用户

发布于 2019-12-05 05:48:57

不是很漂亮,但会完成工作的

代码语言:javascript
运行
复制
void downloadGzip(String dir, String url, String user, String pwd) throws Exception {



    //Authentication
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pwd);
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(new URI(url).getHost(), AuthScope.ANY_PORT), creds);
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);

    CloseableHttpResponse response = HttpClientBuilder.create().build().execute(new HttpGet(url), context);

    //get remote file name
    Header[] headers = response.getHeaders("Content-Disposition");
    String file = headers[0].getValue().substring(headers[0].getValue().lastIndexOf("=") + 1);
    String out = dir + file.substring(0, file.indexOf(".gz"));

    GzipCompressorInputStream stream = new GzipCompressorInputStream(response.getEntity().getContent());
    FileUtils.copyInputStreamToFile(stream, new File(out));
    stream.close();
}
票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6295220

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档