从java应用程序下载文件

嗨我需要一些帮助从我的Java应用程序下载文件。

该url为“http://my.site.com/UICFEWebroot/QueryOneDateAllCur?lang=ita&rate=0&initDay=11&initMonth=10&initYear=2010&refCur=euro&R1=csv”

我尝试使用此代码,但结果是一个空文件

URL urlAgg = new URL(address); int lf = urlAgg.openConnection().getContentLength(); FileOutputStream fos = new FileOutputStream("agg" + File.separator + "cambio" + gg + mm + aaaa + ".csv"); InputStream in = urlAgg.openStream(); for (int i = 0; i < lf; i++) { byte[] b = new byte[1]; in.read(b); fos.write(b); } fos.close(); in.close(); 

这对我有用:

 package download; import java.io.*; import java.net.URL; /** * DownloadDemo * User: Michael * Date: Oct 11, 2010 * Time: 10:19:34 AM */ public class DownloadDemo { public static void main(String[] args) { StringBuilder contents = new StringBuilder(4096); BufferedReader br = null; try { String downloadSite = ((args.length > 0) ? args[0] : "http://www.google.com"); String outputFile = ((args.length > 1) ? args[1] : "currencies.csv"); URL url = new URL(downloadSite); InputStream is = url.openConnection().getInputStream(); br = new BufferedReader(new InputStreamReader(is)); PrintStream ps = new PrintStream(new FileOutputStream(outputFile)); String line; String newline = System.getProperty("line.separator"); while ((line = br.readLine()) != null) { contents.append(line).append(newline); } ps.println(contents.toString()); } catch (Exception e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); } catch(IOException e) { e.printStackTrace(); } } } } 

这是结果的一部分(太大而不适合整个事情):

 C:\JDKs\jdk1.6.0_13\bin\java -Didea.launcher.port=7533 com.intellij.rt.execution.application.AppMain download.DownloadDemo http://uif.bancaditalia.it/UICFEWebroot/QueryOneDateAllCur?lang=ita&rate=0&initDay=11&initMonth=10&initYear=2010&refCur=euro&R1=csv Quotazioni in euro riferite al 11/10/2010""Paese,Valuta,Codice ISO,Codice UIC,Quotazione,Convenzione di cambio,Nota""AFGHANISTAN,Afghani,AFN,115,62.8792,Foreign currency amount for 1 Euro,CAMBI INDICATIVI CALCOLATI GIORNALMENTE DA BI SULLA BASE DELLE RILEVAZIONI DI MERCATOALBANIA,Lek,ALL,047,138.163,Foreign currency amount for 1 Euro,CAMBI INDICATIVI CALCOLATI GIORNALMENTE DA BI SULLA BASE DELLE RILEVAZIONI DI MERCATOALGERIA,Dinaro Algerino,DZD,106,103.035,Foreign currency amount for 1 Euro,CAMBI INDICATIVI CALCOLATI GIORNALMENTE DA BI SULLA BASE DELLE RILEVAZIONI DI MERCATOANGOLA,Readjustado Kwanza,AOA,087,128.395,Foreign currency amount for 1 Euro,CAMBI INDICATIVI CALCOLATI GIORNALMENTE DA BI SULLA BASE DELLE RILEVAZIONI DI MERCATOANTIGUA E BARBUDA,Dollaro Caraibi Est,XCD,137,3.76272,Foreign currency amount for 1 Euro,CAMBI INDICATIVI CALCOLATI GIORNALMENTE DA BI SULLA BASE DELLE RILEVAZIONI DI MERCATOANTILLE OLANDESI,Fiorino Antille Olandesi,ANG,132,2.48061,Foreign currency amount for 1 Euro,CAMBI INDICATIVI CALCOLATI GIORNALMENTE DA BI SULLA BASE DELLE RILEVAZIONI DI MERCATOARABIA SAUDITA,Riyal Saudita,SAR,075,5.22619,Foreign currency amount for 1 Euro,CAMBI INDICATIVI CALCOLATI GIORNALMENTE DA BI SULLA BASE DELLE RILEVAZIONI DI MERCATOARGENTINA,Peso Argentina,ARS,216,5.51578,Foreign currency amount for 1 EuroCAMBI INDICATIVI CALCOLATI GIORNALMENTE DA BI SULLA BASE DELLE RILEVAZIONI DI MERCATO Process finished with exit code 0 

您可以暂时更改“for”子句。 只是为了确保内容长度不正确时下载:

  String urlTemp = "the URL"; File saveFile = new File("File to save path"); URL url = new URL(urlTemp); URLConnection connection = url.openConnection(); InputStream is = connection.getInputStream(); FileOutputStream fos = new FileOutputStream(saveFile); byte[] buffer = new byte[1024]; int read = 0; while ((read = is.read(buffer, 0, buffer.length)) >= 0) { fos.write(buffer, 0, read); } fos.flush(); fos.close(); is.close(); 

还需要try / catch部分。 如果要下载的文件很大,您可能需要在连接对象上设置更长的时间:

 connection .setConnectTimeout(timeoutonnect); connection .setReadTimeout(timeoutRead ); 

希望片段有用!

我总是使用库来跳过这个样板代码。 这是commons / io的一个例子:

 final String url = "http://www.etc.etc"; final String fileName = "/foo/bar/baz.txt"; InputStream in = null; OutputStream out = null; try{ in = new URL(url).openStream(); final File f = new File(fileName); final File par = f.getParentFile(); if(!par.exists() && !par.mkdirs()){ throw new IllegalStateException( "Couldn't create folder " + par); } out = FileUtils.openOutputStream(f); IOUtils.copy(in, out); } catch(final IOException e){ // handle exception } finally{ IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } 

编辑(duffymo):这是实际可运行的表单中的代码:

编辑(seanizer): 将其移动到pastebin