2011-05-26 88 views
0

我能解析一個xml文件,我想下載由xml給出其URL的文件。我有以下代碼:Android:100 KB以上的文件下載成爲1 KB

try{ 
     /* Create a URL we want to load some xml-data from. */ 
     URL url = new URL("http://dev2.eacomm.com/tabletcms/tablets/sync_login/jayem30/jayem"); 
     url.openConnection(); 
     /* Get a SAXParser from the SAXPArserFactory. */ 
     SAXParserFactory spf = SAXParserFactory.newInstance(); 
     SAXParser sp = spf.newSAXParser(); 

     /* Get the XMLReader of the SAXParser we created. */ 
     XMLReader xr = sp.getXMLReader(); 
     /* Create a new ContentHandler and apply it to the XML-Reader*/ 
     ExampleHandler myExampleHandler = new ExampleHandler(); 
     xr.setContentHandler(myExampleHandler); 

     /* Parse the xml-data from our URL. */ 
     xr.parse(new InputSource(url.openStream())); 
     /* Parsing has finished. */ 

     /* Our ExampleHandler now provides the parsed data to us. */ 
     List<ParsedExampleDataSet> parsedExampleDataSet = myExampleHandler.getParsedData(); 

     Iterator i; 
     i = parsedExampleDataSet.iterator(); 
     ParsedExampleDataSet dataItem; 

     while(i.hasNext()){ 
       dataItem = (ParsedExampleDataSet) i.next(); 
       String folder = dataItem.getParentTag(); 

       if(folder == "Videos" ){ 

        String [] videoName = dataItem.getName().split("/"); 
        String currentFile = videoName[0] + "." + videoName[1]; 
        String currentFileURL = dataItem.getUrl() + videoName[0] + "." + videoName[1]; 
        tv.append("\nURL: " + currentFileURL); 


        new DownloadFileAsync().execute(currentFile , currentFileURL, "Videos"); 
        this.videoCount++; 
        tv.append("\nVideo Count: " + this.videoCount); 
       } 

       if(folder == "Slideshows"){ 
        //processSlideshows(dataItem, folder); 
       }  
     } 

    }catch(Exception e){ 
     Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); 
    } 

下載代碼在異步任務上。但是,當我運行這個時,我下載的兩個文件(126kb和98kb)被下載,文件在那裏,但它們的大小都只有1kb。該文件不播放。

當我改變行

**new DownloadFileAsync().execute(currentFile , currentFileURL, "Videos");** 
to 
**new DownloadFileAsync().execute("hehe.flv", "http://dev2.eacomm.com/tabletcms/app/webroot/files/000002/videos/27.flv", "Videos");** 

文件大小是好的,但它返回只有一個文件

編輯:

//---------------------------- START DownloadFileAsync -----------------------// 
class DownloadFileAsync extends AsyncTask<String, String, String>{ 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     showDialog(DIALOG_DOWNLOAD_PROGRESS); 
    } 

    @Override 
    protected String doInBackground(String... strings) { 

     try { 
      String currentFile = strings[0]; 
      String currentFileURL = strings[1]; 
      String folder = strings[2]; 

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

      int lenghtOfFile = c.getContentLength(); 

      FileOutputStream f = new FileOutputStream(new File(root + "/Engagia/Downloads/" + folder, currentFile)); 

      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()); 
     } 
     return null; 
    } 

    protected void onProgressUpdate(String... progress) { 
     Log.d("ANDRO_ASYNC",progress[0]); 
     mProgressDialog.setProgress(Integer.parseInt(progress[0])); 
    } 

    @Override 
    protected void onPostExecute(String unused) { 
     dismissDialog(DIALOG_DOWNLOAD_PROGRESS); 
    } 

} 
//---------------------------- END DownloadFileAsync -----------------------// 

@Override 
protected Dialog onCreateDialog(int id) { 
    switch (id) { 
     case DIALOG_DOWNLOAD_PROGRESS: 
      mProgressDialog = new ProgressDialog(this); 
      mProgressDialog.setMessage("Downloading files..."); 
      mProgressDialog.setIndeterminate(false); 
      mProgressDialog.setMax(100); 
      mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
      mProgressDialog.setCancelable(true); 
      mProgressDialog.show(); 
      return mProgressDialog; 
     default: 
      return null; 
    } 

} 

編輯:(感謝雜亂無章)

我的壞,我重新檢查我的網址,我發現我的XML流不下載返回正確的網址,以便我不得不重建一個URL下載。我做了類似的:

tv.append("\nCurrent File URL: " + currentFileURL); 
String downloadFileURL = currentFileURL.replace("tablets/tablet_content", "app/webroot/files"); 
+1

你有沒有證實,'currentFile'和'currentFileURL'都是正確的嗎?嘗試通過代碼進行調試,以查看它們是否正確形成。 – Haphazard 2011-05-26 13:11:17

+0

嗨,感謝您的回覆,是的,他們都是正確的,我嘗試了其他的網址 – Kris 2011-05-26 13:20:29

+1

你是否從你的下載器得到任何錯誤? 'Log.d(「Downloader」,e.getMessage());'輸出將會非常有趣。此外,這應該是'Log.e'的「錯誤」。 'Log.d'用於「調試」語句。 – Haphazard 2011-05-26 14:09:54

回答

1

確保您的網址正確形成。您是否確認currentFilecurrentFileURL都是正確的?

0

你可以發佈你的代碼是在異步任務。我覺得這個問題是從url下載文件。

請參閱以下URL以獲取如何下載文件。

ANDROID: How do I download a video file to SD card?

感謝 迪帕克

+0

嗨,感謝您的回覆@Deepak,我更新了問題,現在用下載代碼:) – Kris 2011-05-26 13:33:23

0

請嘗試下面的代碼。

package com.endeavour.sampleprograms; 

import java.io.BufferedInputStream; 
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 java.net.URLConnection; 

import org.apache.http.util.ByteArrayBuffer; 

import android.os.AsyncTask; 
import android.os.Environment; 

class DownloadFileAsync extends AsyncTask<String, String, String>{ 

    private static final String DIALOG_DOWNLOAD_PROGRESS = null; 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
//  showDialog(DIALOG_DOWNLOAD_PROGRESS); 
    } 

    @Override 
    protected String doInBackground(String... strings) { 

     try { 
      String currentFile = strings[0]; 
      String currentFileURL = strings[1]; 
      String folder = strings[2]; 
*emphasized text* 
      String fileName = Environment.getExternalStorageDirectory() + "/Engagia/Downloads/" + folder+"/"; 
      File wallpaperDirectory = new File(fileName); 
      if (!wallpaperDirectory.exists()) 
       wallpaperDirectory.mkdirs(); 
      fileName = fileName+currentFile; 
      downloadFromUrl(currentFileURL, fileName); 
      //   FileOutputStream f = new FileOutputStream(new File(root + "/Engagia/Downloads/" + folder, currentFile)); 

     }catch (Exception e){ 

     } 
     return null; 
    } 


    public void downloadFromUrl(String VideoURL, String fileName) { //this is the downloader method 
     try { 
      System.out.println("....Url....."+VideoURL); 
       URL url = new URL(VideoURL); //you can write here any link 
       File file = new File(fileName); 

       long startTime = System.currentTimeMillis(); 
           /* Open a connection to that URL. */ 
       URLConnection ucon = url.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(50); 
       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.close(); 


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




} 

感謝迪帕克