Android:如何更改下载文件的文件名?

时间:2011-05-06 03:18:00

标签: java android url download filenames

我想在xml文件的帮助下更改我从互联网上下载的文件的文件名:

<?xml version="1.0" encoding="ISO-8859-1" ?> 
<Phonebook>
    <PhonebookEntry>
        <firstname>Michael</firstname> 
        <lastname>De Leon</lastname> 
        <Address>5, Cat Street</Address> 
        <FileURL>http://www.technobuzz.net/wp-content/uploads/2009/09/Android-Emulator.jpg</FileURL> 
    </PhonebookEntry>
    <PhonebookEntry>
        <firstname>John</firstname> 
        <lastname>Smith</lastname> 
        <Address>6, Dog Street</Address> 
        <FileURL>http://www.cellphonehits.net/uploads/2008/10/android_openmoko.jpg</FileURL> 
    </PhonebookEntry>
    <PhonebookEntry>
        <firstname>Jember</firstname> 
        <lastname>Dowry</lastname> 
        <Address>7, Monkey Street</Address> 
        <FileURL>http://www.techdigest.tv/android.jpg</FileURL> 
    </PhonebookEntry>
</Phonebook>

我的程序包含以下代码:

package com.example.parsingxml;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
public class ParsingXML extends Activity {

    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private ProgressDialog mProgressDialog;
    public String FileName = "";
    public String FileURL = "";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
         super.onCreate(icicle);

         /* Create a new TextView to display the parsingresult later. */
         TextView tv = new TextView(this);
         tv.setText("This is the parsing program...");


         try {
              /* Create a URL we want to load some xml-data from. */
              URL url = new URL("http://cloud.eacomm.com/jm/sampleXML.xml");
              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();

              /* Set the result to be displayed in our GUI. */
              //tv.setText(parsedExampleDataSet.toString());
              Iterator i;
              i = parsedExampleDataSet.iterator();
              ParsedExampleDataSet dataItem;
              while(i.hasNext()){

                   dataItem = (ParsedExampleDataSet) i.next();
                   tv.append("\n" + dataItem.getfirstname());
                   tv.append("\n" + dataItem.getFileURL());
                   tv.append("\n" + dataItem.getAddress());
                   this.FileName = dataItem.getfirstname() + ".jpg";
                   this.FileURL = dataItem.getFileURL();
                   startDownload();

              }

         } catch (Exception e) {
              /* Display any Error to the GUI. */
              tv.setText("Error: " + e.getMessage());

         }
         /* Display the TextView. */
         this.setContentView(tv);
    }

    private void startDownload(){
        new DownloadFileAsync().execute(FileURL);
    }

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


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

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


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

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

            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);
       }


    }

}

正如你所看到的,下载文件的文件名应该是.jpg,但是当我查看我的sdcard / download /时,唯一下载的文件是Jember.jpg。我相信它只会覆盖其他两个文件。我如何输出Michael.jpg,John.jpg和Jember.jpg?

2 个答案:

答案 0 :(得分:1)

很简单,因为您正在使用实例变量(FileUrl,FileName)来下载/存储文件,而不是您传递给AsyncTask的值。在调用AsyncTask时执行此操作:

  new DownloadFileAsync().execute(currentUrl, currentFile);

然后,在doInBackground中:

  @Override
  protected String doInBackground(String... strings) {
    String url = strings[0];
    String fileName = strings[1];
    ...
  }

答案 1 :(得分:0)

你的问题是这个......

while(i.hasNext()) {
    ...
    this.FileName = dataItem.getfirstname() + ".jpg";
    ...
    startDownload();
}

基本上,startDownload()只是启动一个AsyncTask,这意味着它会立即返回。在while循环中运行意味着FileName最终将成为最后一个(最有可能)在任何AsyncTasks完成之前。

我几乎将try/catch方法的onCreate()块中的所有内容重新定位到DownloadFileAsync doInBackground()中,只创建一个实例并让它处理解析和迭代。