无法从Android应用中下载互联网托管的文本文件

时间:2015-03-01 17:25:23

标签: android url android-asynctask network-protocols filenotfoundexception

我正在开发一个Android应用程序,我需要在其中下载托管在的文本文件: - https://www.dropbox.com/s/2smsdqknrjg5zda/try1.txt/?dl=0

从我的应用内部获取/加载其文本视图中的内容。 我正在使用 AsyncTask的doInBackground()方法进行下载。

这是我到目前为止提出的MainActivity.java中的代码。 该文件已在 /storage/sdcard/file_try7.ext 中下载,但由于某种原因,我在DDMS中看到它的大小为0.

在LogCat部分,我收到消息" java.io.FileNotFoundException "。

有人可以看看,看看问题可能是什么.. ??

package com.example.xxxxx;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.text.InputFilter.LengthFilter;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;
import android.os.Build;
import android.provider.MediaStore;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container,
                    false);
            return rootView;
        }
    }

    private class MyAsyncTask extends AsyncTask<Void, Void, Void>{

        //execute on background (out of the UI thread)




    @Override
    protected Void doInBackground(Void... params) {
        try {
            //set the download URL, a url that points to a file on the internet
            //this is the file to be downloaded


            URL url = new URL("https://www.dropbox.com/s/2smsdqknrjg5zda/try1.txt/?dl=0");

            //create the new connection
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            //set up some things on the connection
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);

            //and connect!
            urlConnection.connect();

            //set the path where we want to save the file
            //in this case, going to save it on the root directory of the
            //sd card.
            File SDCardRoot = Environment.getExternalStorageDirectory();
            //create a new file, specifying the path, and the filename
            //which we want to save the file as.
            File file = new File(SDCardRoot,"menu7.ext");
    //        if (!file.exists()) {
      //          file.createNewFile();
        //    }

            //this will be used to write the downloaded data into the file we created
            FileOutputStream fileOutput = new FileOutputStream(file);

            //this will be used in reading the data from the internet
            InputStream inputStream = urlConnection.getInputStream();

            //this is the total size of the file
            int totalSize = urlConnection.getContentLength();
            //variable to store total downloaded bytes
            int downloadedSize = 0;

            //create a buffer...
            byte[] buffer = new byte[1024];
            int bufferLength = 0; //used to store a temporary size of the buffer

            //now, read through the input buffer and write the contents to the file
            while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                    //add the data in the buffer to the file in the file output stream (the file on the sd card
                    fileOutput.write(buffer, 0, bufferLength);
                    //add up the size so we know how much is downloaded
                    downloadedSize += bufferLength;
                    //this is where you would do something to report the prgress, like this maybe
                    //updateProgress(downloadedSize, totalSize);

            }
            //close the output stream when done
            fileOutput.close();

    //catch some possible errors...
    } catch (MalformedURLException e) {
            e.printStackTrace();
    } catch (IOException e) {
            e.printStackTrace();
    }
        // TODO Auto-generated method stub
        return null;
    }


}
    public void get_menu(View v)
    {
        MyAsyncTask async = new MyAsyncTask();
        async.execute();
        //Toast.makeText(this.getApplicationContext(),"Inside get_menu",Toast.LENGTH_SHORT).show();
            }

    //Method to get the FileInputStream object as a string.
            public static String convertStreamToString(InputStream is) throws Exception {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                  sb.append(line).append("\n");
                }
                reader.close();
                return sb.toString();
            }

            /*Method to get text of the file with path as filePath as string by calling 
              convertStreamToString.*/
            public static String getStringFromFile (String filePath) throws Exception {
                File fl = new File(filePath);
                FileInputStream fin = new FileInputStream(fl);
                String ret = convertStreamToString(fin);
                fin.close();        
                return ret;
          }



    public void load_menu(View v)
    {
        //Method which actually loads the text by calling the getStringFromFile method.
            String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
            EditText editText2=(EditText)findViewById(R.id.editText2);
            //String fileName=editText2.getText().toString();
            String path  = baseDir + "/" + "menu7" + ".ext";

            try {
                    String inp_string=getStringFromFile(path);
                //EditText editText1=(EditText)findViewById(R.id.editText1);
                editText2.setText(inp_string);
            } catch (Exception e) {
                Toast.makeText(this.getApplicationContext(),"File not found.",Toast.LENGTH_SHORT).show();
                // TODO Auto-generated catch block
                e.printStackTrace();
            }





    }

}

1 个答案:

答案 0 :(得分:0)

您正在通过get方法打开网址,这就是为什么它没有在缓冲区中提供输出文件,而是下载文件的链接。检查下面的屏幕截图。确保下载文件,然后将文件放入缓冲区。但我想知道如果你已经下载了文件,为什么还要这样做呢。

http://i.stack.imgur.com/w6AnN.png