2013-09-23 15 views
0

我編寫了一個Android應用程序來下載文件並在進度條中顯示進度。爲此,我需要知道文件的長度。有時(或者更確切地說)它確實發生了-1的長度使用Android下載文件和fileLength是-1

int fileLength = connection.getContentLength();

爲什麼發生?有沒有辦法避免它,並獲得正確的長度?

package com.example.asynctaskexample; 

import java.io.BufferedInputStream; 
import java.io.FileOutputStream; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.net.URLConnection; 



import android.os.AsyncTask; 
import android.os.Bundle; 
import android.os.SystemClock; 
import android.app.Activity; 
import android.app.ProgressDialog; 
import android.util.Log; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.ProgressBar; 

public class MainActivity extends Activity { 
// declare the dialog as a member field of your activity 
ProgressBar prgs; 
Button showProgressBtn; 
Button stopProgressBtn; 
int fileLength; 
long total; 
//ProgressDialog mProgressDialog; 
DownloadFile downloadFile = new DownloadFile(); 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    prgs = (ProgressBar) findViewById(R.id.progress); 
    showProgressBtn = (Button) findViewById(R.id.btn); 
    showProgressBtn.setOnClickListener(new OnClickListener() { 
     public void onClick(View v) { 
      showProgress(); 
     } 
    }); 
    stopProgressBtn = (Button) findViewById(R.id.btnCancel); 
    stopProgressBtn.setOnClickListener(new OnClickListener() { 
     public void onClick(View v) { 
      stopProgress(); 
     } 
    }); 

} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 

public void showProgress() { 
    try { 
     downloadFile.execute("http://www.collegeneedscorner.com/mydata.dat"); 
    } catch(Exception e) { 
     e.getStackTrace(); 
    } 
    Log.v("Download", "Started"); 

} 

public void stopProgress() { 
downloadFile.cancel(true); 
} 


// usually, subclasses of AsyncTask are declared inside the activity class. 
// that way, you can easily modify the UI thread from here 
public class DownloadFile extends AsyncTask<String, Integer, String> { 

    protected void onPreExecute() { 
     super.onPreExecute(); 
     prgs.setMax(100); 
    } 

    protected void onCancelled() { 
     prgs.setMax(0); 
     Log.v("Progress","Cancelled"); 
    } 

    protected String doInBackground(String... sUrl) { 
     try { 
      URL url = new URL(sUrl[0]); 
      URLConnection connection = url.openConnection(); 
      connection.connect(); 
      // this will be useful so that you can show a typical 0-100% progress bar 
      fileLength = connection.getContentLength(); 
      //With the following it no longer works 
      //final String fileLengthS = connection.getHeaderField("Content-Length"); 
      //Log.v("fileLengthS = ", fileLengthS); 
      if (fileLength == -1) 
       fileLength = 315; 
      Log.v("fileLength=","" + fileLength); 
      // download the file 
      InputStream input = new BufferedInputStream(url.openStream()); 
      OutputStream output = new FileOutputStream("/sdcard/mydata.dat"); 

      byte data[] = new byte[64]; 
      total = 0; 
      int count; 
      while ((count = input.read(data)) != -1) { 
       total += count; 
       // publishing the progress.... 
       publishProgress((int) (total * 100/fileLength)); 
       SystemClock.sleep(1000); 
       output.write(data, 0, count); 
      } 

      output.flush(); 
      output.close(); 
      input.close(); 
     } catch (Exception e) { 
      e.getStackTrace(); 
     } 
     return null; 
    } 

    protected void onProgressUpdate(Integer... values) { 
     super.onProgressUpdate(values); 
     //increment progress bar by progress value 
     prgs.setProgress(values[0]); 
    } 

} 

}

回答

1

嘗試如上使用URLConnection.getContentLength。如果服務器沒有指定長度,那麼你無法知道。

檢查了這一點LinkLink

+0

我發現了一些有用的相關信息在這裏,但它並沒有爲我工作。這是鏈接:[鏈接](http://stackoverflow.com/questions/2983073/how-to-know-the-size-of-a-file-before-downloading-it/12271781#12271781) – Monica

+0

儘快當我添加使用HTTP頭獲取文件長度的句子時,應用程序不再起作用。我想知道爲什麼會發生這種情況。 – Monica

+0

你能上傳你的代碼嗎? – vish