2011-04-27 129 views

回答

2

你可以做這樣的事情......

當你決定開始下載:

new Thread(new Runnable() 
    { 
    @Override 
    public void run() 
     { 
     File out; 
     Downloader DDL; 
     DDL=new Downloader(); 
     out=new File(Environment.getExternalStorageDirectory() + "/DestFileName.txt"); 
     DDL.DownloadFile("SourceURL",out); 

     } 
    }).start(); 

凡下載類

public class Downloader { 

public void Downloader() 
     { 
    // TODO Auto-generated method stub 
    } 

public boolean DownloadFile(String url, File outputFile) 
    { 
    try { 
     URL u = new URL(url); 
     URLConnection conn = u.openConnection(); 
     int contentLength = conn.getContentLength(); 

     DataInputStream stream = new DataInputStream(u.openStream()); 

     byte[] buffer = new byte[contentLength]; 
     stream.readFully(buffer); 
     stream.close(); 

     DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile)); 
     fos.write(buffer); 
     fos.flush(); 
     fos.close(); 
     } 
    catch(FileNotFoundException e) 
     { 
     return false; 
     } 
    catch (IOException e) 
     { 
     return false; 
     } 

    return true; 
    } 
} 
0

使用此函數用於下載文件在SD卡

public void downloadNauhe(String url) { 

    class DownloadFile extends AsyncTask<String, Integer, String> { 
     @Override 
     protected String doInBackground(String... url) { 
      int count; 
      try { 
       URL url1 = new URL("http://downloads.hussainiat.com/nauhey/arsalan_haider/vol_2011_-_12/01_tum_jawab_e_zulm_dogay_-_arsalan_haider_2011_-_2012.mp3"); 
       URLConnection conexion = url1.openConnection(); 
       conexion.connect(); 
       int lenghtOfFile = conexion.getContentLength(); 
       InputStream input = new BufferedInputStream(url1.openStream()); 
       OutputStream output = new FileOutputStream("/sdcard/01_manum_abbas_as_-_mesum_abbas_2012.mp3"); 
       byte data[] = new byte[1024]; 
       long total = 0; 
       System.out.println("downloading............."); 
       while ((count = input.read(data)) != -1) { 
        total += count; 
        publishProgress((int)((total/(float)lenghtOfFile)*100)); 
        output.write(data, 0, count);     
       } 
       output.flush(); 
       output.close(); 
       input.close(); 
      } catch (Exception e) { 
      } 

      return null; 
     } 

     @Override 
     protected void onProgressUpdate(Integer... values) { 
      super.onProgressUpdate(values); 
      mprBar.setProgress(values[0]); 
     } 
    } 
    DownloadFile downloadFile = new DownloadFile(); 
    downloadFile.execute(url); 
} 

Don'forget添加權限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission> 
<uses-permission android:name="android.permission.INTERNET"></uses-permission>