Android:无法从服务器下载文件(FileNotFoundException)

时间:2014-12-30 06:09:02

标签: android download filenotfoundexception

我试图从服务器下载文件。代码如下:

代码:

class download_file extends AsyncTask<Void, Void, Void> 
    {

        @Override
        protected void onPreExecute() 
        {
            super.onPreExecute();
            showProgressdialog(""+selected_file_url);
        }

        @Override
        protected Void doInBackground(Void... params) 
        {
            String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/MYFOLDER/";
            try 
            {
                URL url = new URL(selected_file_url);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.setDoOutput(true);

                //connect
                urlConnection.connect();

                //set the path where we want to save the file           
                File SDCardRoot = Environment.getExternalStorageDirectory();   

                File dirr = new File(fullPath);
                if (!dirr.exists()) {dirr.mkdirs();}                            
                File file = new File(fullPath, selected_file_name +".xls");                 

                if(file.exists())
                    file.delete();
                file.createNewFile();

                FileOutputStream fileOutput = new FileOutputStream(file);
                InputStream inputStream = urlConnection.getInputStream();
                totalSize = urlConnection.getContentLength();
                showProgressdialog(selected_file_url);
                getActivity().runOnUiThread(new Runnable() 
                {
                    public void run() 
                    {
                        pb.setMax(totalSize);
                    }               
                });

                //create a buffer...
                byte[] buffer = new byte[2048];
                int bufferLength = 0;

                while ( (bufferLength = inputStream.read(buffer)) > 0 ) 
                {
                    fileOutput.write(buffer, 0, bufferLength);
                    downloadedSize += bufferLength;
                    // update the progressbar //
                    getActivity().runOnUiThread(new Runnable() 
                    {
                        public void run() 
                        {
                            pb.setProgress(downloadedSize);
                            float per = ((float)downloadedSize/totalSize) * 100;
                            tv_download_message.setText("Downloaded " + downloadedSize + "KB / " + totalSize + "KB (" + (int)per + "%)" );
                        }
                    });
                }
                fileOutput.close();
                getActivity().runOnUiThread(new Runnable() 
                {
                    public void run() 
                    {
                        // pb.dismiss(); // if you want close it..
                    }
                });         

            } catch (final MalformedURLException e) {
                showError("Error : MalformedURLException " + e);        
                e.printStackTrace();
            } catch (final IOException e) {
                showError("Error : IOException " + e);          
                e.printStackTrace();
            }
            catch (final Exception e) {
                showError("Error : Please check your internet connection " + e);
            }  
            return null;
        }


        @Override
        protected void onPostExecute(Void result) 
        {
            dialog.dismiss();
        }
    }

并通过

调用上面的下载
                    selected_file_url = file_url_list[position];
                    selected_file_name = temp[2];
                    new download_file().execute();

问题:

弹出

的错误消息
`ERROR: IOException java.io.FileNotFoundException" + <link> 

但是,我已经测试了网络浏览器中的链接,该文件可以成功下载到我的桌​​面。

上述代码出了什么问题?

1 个答案:

答案 0 :(得分:0)

试试这个简单的例子:

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

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

public class download extends Activity {

    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private Button startBtn;
    private ProgressDialog mProgressDialog;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        startBtn = (Button)findViewById(R.id.startBtn);
        startBtn.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                startDownload();
            }
        });
    }

    private void startDownload() {
        String url = "http://yoursite"; //your download url
        new DownloadFileAsync().execute(url);
    }
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_DOWNLOAD_PROGRESS:
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Downloading file..");
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setCancelable(false);
            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) {
        int count;

    try {

    URL url = new URL(aurl[0]);
    URLConnection conexion = url.openConnection();
    conexion.connect();

    int lenghtOfFile = conexion.getContentLength();
    Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

    InputStream input = new BufferedInputStream(url.openStream());
    OutputStream output = new FileOutputStream("/sdcard/YOURFLIENAME.XLS"); //save file in SD Card

    byte data[] = new byte[1024];

    long total = 0;

        while ((count = input.read(data)) != -1) {
            total += count;
            publishProgress(""+(int)((total*100)/lenghtOfFile));
            output.write(data, 0, count);
        }

        output.flush();
        output.close();
        input.close();
    } catch (Exception e) {}
    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);
    }
}
}

AndroidManifest.xml - 为应用提供必要的权限

由于我们要从互联网上下载文件并将其存储在SD卡上,我们需要为我们的应用程序提供两项特定权限。确保 AndroidManifest.xml 文件中包含以下行:

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

如需进一步参考,您可以查看this示例。