Java 安卓:文件下载100+;KB变为1KB

Java 安卓:文件下载100+;KB变为1KB,java,android,xml,download,Java,Android,Xml,Download,我能够解析一个xml文件,我想下载xml给定url的文件。我有以下代码: 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

我能够解析一个xml文件,我想下载xml给定url的文件。我有以下代码:

    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();
    }
文件大小正常,但只返回一个文件

编辑:

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

}

可以发布异步任务中的代码吗。我觉得问题在于从url下载文件

请参阅以下url以了解如何下载文件

谢谢
Deepak

确保URL格式正确。您确认了
currentFile
currentFileURL
都是正确的吗?

请尝试以下代码

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




}
package com.奋进.sampleprograms;
导入java.io.BufferedInputStream;
导入java.io.File;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.net.HttpURLConnection;
导入java.net.URL;
导入java.net.URLConnection;
导入org.apache.http.util.ByteArrayBuffer;
导入android.os.AsyncTask;
导入android.os.Environment;
类DownloadFileAsync扩展AsyncTask{
私有静态最终字符串对话框\u下载\u进度=null;
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
//showDialog(对话框下载进度);
}
@凌驾
受保护的字符串背景(字符串…字符串){
试一试{
String currentFile=字符串[0];
String currentFileURL=字符串[1];
字符串文件夹=字符串[2];
*强调文本*
字符串fileName=Environment.getExternalStorageDirectory()+“/Engagia/Downloads/”+folder+“/”;
文件目录=新文件(文件名);
如果(!wallperDirectory.exists())
wallperDirectory.mkdirs();
文件名=文件名+当前文件;
downloadFromUrl(currentFileURL,文件名);
//FileOutputStream f=新的FileOutputStream(新文件(root+“/Engagia/Downloads/”+文件夹,currentFile));
}捕获(例外e){
}
返回null;
}
public void downloadFromUrl(字符串VideoURL,字符串文件名){//这是下载程序方法
试一试{
System.out.println(“…Url…”+视频Url);
URL=newURL(VideoURL);//您可以在此处写入任何链接
文件=新文件(文件名);
long startTime=System.currentTimeMillis();
/*打开到该URL的连接*/
URLConnection ucon=url.openConnection();
/*
*定义要从URLConnection读取的InputStreams。
*/
InputStream=ucon.getInputStream();
BufferedInputStream bis=新的BufferedInputStream(is);
/*
*将字节读取到缓冲区,直到没有更多内容可读取(-1)。
*/
ByteArrayBuffer baf=新ByteArrayBuffer(50);
int电流=0;
而((当前=bis.read())!=-1){
baf.append((字节)当前值);
}
/*将读取的字节转换为字符串*/
FileOutputStream fos=新的FileOutputStream(文件);
fos.write(baf.toByteArray());
fos.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
}

谢谢Deepak

您确认了
currentFile
currentFileURL
都是正确的吗?请试着调试代码,看看它们的格式是否正确。您好,谢谢您的回复,是的,它们都是正确的,我实际尝试了其他URL。您的下载程序是否有任何错误<代码>Log.d(“Downloader”,例如getMessage())输出将非常有趣。对于“错误”,也应该是
Log.e
Log.d
用于“调试”语句。您好@happad,我的错,您说得对,我的URL格式不正确,非常感谢!)伟大的我添加了一个答案,以便您可以正确地关闭此问题。您好,谢谢您的回复@Deepak,我更新了问题,现在下载代码:)
tv.append("\nCurrent File URL: " + currentFileURL);
String downloadFileURL = currentFileURL.replace( "tablets/tablet_content", "app/webroot/files" );
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();
        }
    }




}