2012-07-31 5 views

Répondre

4
public void downloadFromUrl(String url, String outputFileName) { 


    File dir = new File(Environment.getExternalStorageDirectory() + "/"); 
    if (dir.exists() == false) { 
     dir.mkdirs(); 
    } 
    try { 
     URL downloadUrl = new URL(url); // you can write any link here 

     File file = new File(dir, outputFileName);   
     /* Open a connection to that URL. */ 
     URLConnection ucon = downloadUrl.openConnection(); 

     /* 
     * Define InputStreams to read from the URLConnection. 
     */ 
     InputStream is = ucon.getInputStream(); 
     BufferedInputStream bis = new BufferedInputStream(is); 

     /* 
     * Read bytes to the Buffer until there is nothing more to read(-1). 
     */ 
     ByteArrayBuffer baf = new ByteArrayBuffer(5000); 
     int current = 0; 
     while ((current = bis.read()) != -1) { 
      baf.append((byte) current); 
     } 

     /* Convert the Bytes read to a String. */ 
     FileOutputStream fos = new FileOutputStream(file);   
     fos.write(baf.toByteArray()); 
     fos.flush(); 
     fos.close(); 




    } catch (IOException e) { 
     e.printStackTrace(); 


    } 



} 
+0

merci .. cela fonctionne – TheReaper

+0

Cela fonctionne comme un charme ... Pour parfois, il peut jeter "networkOnMainThreadException". Dans ce cas faire ce processus dans AsnycTask et ce serait bien. –

+0

Fonctionne comme un charme. Merci beaucoup :) –

0

Utilisez DownloadManager pour télécharger l'URL, bien que je ne sache pas s'il existe des redirections, DownloadManager s'en chargera.

+0

Wow, je ne comprends pas votre exemple impressionnant avec des connexions de la vôtre et managements et le vôtre InputStreams ... Je lis la documentation .... mais je ne sais pas comment je peux mettre « static public String COLUMN_REASON » mmm ... (ironie) – delive

Questions connexes