[英]Write program to download .gz file in java?
我一直在嘗試在java中編寫一個程序,可以為我從ftp在線服務器下載多個.gz文件。 這是我一直在使用的:
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 的無限循環等等。
當我手動下載此文件時,它會解壓縮並且一切正常,所以我知道這不是文件的問題。
任何建議將不勝感激! 太感謝了!
當我打印出您下載的文件的內容時,它顯示為
-r--r--r-- 1 ftp anonymous 2311751 Jan 29 16:45 GSE10_family.soft.gz
如果我下載文件而不是目錄,我會得到一個 gzip 文件。
$ gunzip GSE10_family.soft.gz
$ ls -l GSE10_family.soft
----------+ 1 peter None 7698802 2011-06-09 16:24 GSE10_family.soft
不是超級漂亮,但會完成工作
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.