2012-12-09 50 views

回答

1

這應該做的伎倆。它將文件下載到sdcard/Download/products.txt。您可以在下面更改它。

try { 
    URL url = new URL("http://base.google.com/base/products.txt"); 
    URLConnection conexion = url.openConnection(); 
    conexion.connect(); 
    int lenghtOfFile = conexion.getContentLength(); 
    InputStream is = url.openStream(); 
    File testDirectory = new File(Environment.getExternalStorageDirectory() + "/Download"); 
    if (!testDirectory.exists()) { 
     testDirectory.mkdir(); 
    } 
    FileOutputStream fos = new FileOutputStream(testDirectory + "/products.txt"); 
    byte data[] = new byte[1024]; 
    long total = 0; 
    int count = 0; 
    while ((count = is.read(data)) != -1) { 
     total += count; 
     int progress_temp = (int) total * 100/lenghtOfFile; 
     /*publishProgress("" + progress_temp); //only for asynctask 
     if (progress_temp % 10 == 0 && progress != progress_temp) { 
      progress = progress_temp; 
     }*/ 
     fos.write(data, 0, count); 
    } 
    is.close(); 
    fos.close(); 
} catch (Exception e) { 
    Log.e("ERROR DOWNLOADING", "Unable to download" + e.getMessage()); 
} 
+0

初始化變量'progress'後引用了一個未知變量'count'。我安全地認爲'count'應該是'progress'? – Adam

+0

對不起!添加'int count';它可以被訪問。編輯我的答案! – MrYanDao

相關問題