2011-05-04 50 views
0

我正在嘗試從URL下載文件。我的代碼不會返回錯誤,但我無法看到我應該在我的內部存儲器中下載的文件。這裏是我的代碼:Android:下載文件代碼不起作用

package com.example.downloadfile; 

import java.io.BufferedOutputStream; 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 

import android.app.Activity; 
import android.os.Bundle; 
import android.os.Environment; 
import android.util.Log; 
import android.widget.TextView; 

public class DownloadFile extends Activity { 

    private static String fileName = "al.jpg"; 

    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     TextView tv = new TextView(this); 
     tv.setText("This is download file program... "); 

     try { 
      URL url = new URL("http://www.fullissue.com/wp-content/uploads/2010/12/Adam-Lambert.jpg"); 
      HttpURLConnection c = (HttpURLConnection) url.openConnection(); 
      c.setRequestMethod("GET"); 
      c.setDoOutput(true); 
      c.connect(); 

      String PATH = Environment.getDataDirectory() + "/"; 

      tv.append("\nPath > " + PATH); 

      Log.v("log_tag", "PATH: " + PATH); 
      File file = new File(PATH); 
      file.mkdirs(); 
      File outputFile = new File(file, fileName); 
      FileOutputStream fos = new FileOutputStream(outputFile); 

      InputStream is = c.getInputStream(); 

      byte[] buffer = new byte[1024]; 
      int len1 = 0; 
      while ((len1 = is.read(buffer)) != -1) { 
       fos.write(buffer, 0, len1); 
      } 
      fos.close(); 
      is.close(); 
     } catch (IOException e) { 
      Log.d("log_tag", "Error: " + e); 
     } 
     Log.v("log_tag", "Check: "); 

     tv.append("\nAnother append!"); 
     this.setContentView(tv); 
    } 

} 

我是新來的Java和Android開發人員,任何答案,將不勝感激,謝謝!


喲!我用了ff。代碼。這對我有用。感謝你的幫助!

private static String fileName = "beautiful_galaxy - tarantula.jpg"; 
private static String fileURL = "http://apod.nasa.gov/apod/image/0903/tarantula2_hst_big.jpg"; 

    try { 
     File root = Environment.getExternalStorageDirectory(); 
     URL u = new URL(fileURL); 
     HttpURLConnection c = (HttpURLConnection) u.openConnection(); 
     c.setRequestMethod("GET"); 
     c.setDoOutput(true); 
     c.connect(); 

     int lenghtOfFile = c.getContentLength(); 

     FileOutputStream f = new FileOutputStream(new File(root + "/download/", fileName)); 

     InputStream in = c.getInputStream(); 

     byte[] buffer = new byte[1024]; 
     int len1 = 0; 
     long total = 0; 

     while ((len1 = in.read(buffer)) > 0) { 
      total += len1; //total = total + len1 
      //publishProgress("" + (int)((total*100)/lenghtOfFile)); 
      f.write(buffer, 0, len1); 
     } 
     f.close(); 
    } catch (Exception e) { 
     Log.d("Downloader", e.getMessage()); 
    } 
+0

嗯......我不認爲數據目錄在非根源手機中是可見的。 – dmon 2011-05-04 04:31:05

+0

@dmon:我嘗試使用Environment.getExternalStorageDirectory()並得到相同的結果,它仍然是關於平板生根(因爲現在使用平板電腦)? – Kris 2011-05-04 06:33:01

回答

3

如果您正在下載文件到SD卡,然後確保你的SD卡安裝,代碼會下載文件到SD卡,如果仍然得到問題讓我知道。

 
try { 
      URL url = new URL(provide any URL); 
      HttpURLConnection c = (HttpURLConnection) url.openConnection(); 
      c.setRequestMethod("GET"); 
      c.setDoOutput(true); 
      c.connect(); 

      String PATH = Environment.getExternalStorageDirectory() 
        + "/download/"; 
      Log.v(LOG_TAG, "PATH: " + PATH); 
      File file = new File(PATH); 
      file.mkdirs(); 

      String fileName = "Test.mp3"; 


      File outputFile = new File(file, fileName); 
      FileOutputStream fos = new FileOutputStream(outputFile); 

      InputStream is = c.getInputStream(); 

      byte[] buffer = new byte[1024]; 
      int len1 = 0; 
      while ((len1 = is.read(buffer)) != -1) { 

       fos.write(buffer, 0, len1); 

      } 
      fos.close(); 
      is.close(); 

      // } 
     } catch (IOException e) { 
      Log.d(LOG_TAG, "Error: " + e); 
      Toast.makeText(myApp, "error " + e.toString(), Toast.LENGTH_LONG) 
        .show(); 

     } 


好運:)

0

我看到這個talk的傢伙說,你應該使用Apache HTTP client而不是Java的一個

下面的代碼片段採取從tutorial

HttpClient httpclient = new DefaultHttpClient(); 
HttpGet httpget = new HttpGet("http://localhost/"); 
HttpResponse response = httpclient.execute(httpget); 
HttpEntity entity = response.getEntity(); 
if (entity != null) { 
    InputStream instream = entity.getContent(); 
    int l; 
    byte[] tmp = new byte[2048]; 
    while ((l = instream.read(tmp)) != -1) { 
    } 
} 
+0

你有樣品代碼嗎?感謝您的回覆 – Kris 2011-05-04 03:54:56

0

很肯定(如@dmon說)你不能以這種方式寫入數據目錄。您想要:

  1. 使用Environment.getDownloadCacheDirectory()Environment.getExternalStorageDirectory()。看看http://developer.android.com/reference/android/os/Environment.html#getDataDirectory%28%29的javadoc。
  2. 使用URLConnection()很好:這是標準的java,並且工作得很好。
  3. 安卓日誌說什麼?
+0

@Fermi:我嘗試使用Environment.getExternalStorageDirectory(),因此下載的文件將存儲到我的SD卡,但仍然無法看到下載的文件。 對不起,我沒有安卓日誌,是否有其他方式來獲取此錯誤,我正在編譯APK文件,然後通過閃存驅動器將其傳輸到我的平板電腦。 – Kris 2011-05-04 06:30:37

+0

嘗試使用它來顯示異常:'Toast.makeText(this,e.getMessage(),Toast.LENGTH_LONG).show();'看看它顯示了什麼。 – Femi 2011-05-04 07:25:18

+0

它顯示「sdcard/download/al.jpg」,但該文件不存在... – Kris 2011-05-04 08:33:10

-2

要下載我用下面的代碼文件:

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

檢查清單文件以下權限:

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

你將有一個NetworkOnMainThreadException現在。看看日誌貓。把你的互聯網代碼放在一個asynctask或線程中。