Download file from java application

2019-04-12 09:08发布

问题:

Hi I need some help to download a file from my java application.

The URL is "http://my.site.com/UICFEWebroot/QueryOneDateAllCur?lang=ita&rate=0&initDay=11&initMonth=10&initYear=2010&refCur=euro&R1=csv"

I try using this code but the result is an empty file

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();

回答1:

This worked for me:

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(); }
        }
    }
}

And here's part of the result (too big to fit the whole thing):

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


回答2:

You can change the "for" clause for a while. Just to ensure the download if the content length is not correct:

 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();

Also try /catch section will be needed. If the file to down load is big you may need to set a bigger time out on the connection object:

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

Hope the snippet help!



回答3:

I would always use a library to skip this boilerplate code. This is an example with 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);
}

Edit (duffymo): Here's the code in a form that's actually runnable:

Edit (seanizer): moved that to pastebin