使用AsyncTask下载文件

时间:2019-02-17 08:43:04

标签: android download android-asynctask

我尝试使用发现的许多代码通过AsyncTask下载文件,但均未成功。 我在logcat上收到错误消息:E/Error:: No such file or directory。 尽管正在寻找该错误的解决方案,但找不到丢失或错误的地方。

这是doInBackground方法,我认为其中缺少某些内容/错误:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);

    new DownloadJSON().execute("http://api.androidhive.info/json/movies.json");
}

protected String doInBackground(String...fileUrl) {
        int count;
        try {
            String root = "data/data/com.example.jsonapp2";

            URL url = new URL(fileUrl[0]);

            URLConnection connection = url.openConnection();
            connection.connect();

            // input stream to read file - with 8k buffer
            InputStream input = new BufferedInputStream(url.openStream(), 8192);

            File fileName = new File(root+"/movies.json");
            boolean existsOrNot = fileName.createNewFile(); // if file already exists will do nothing

            // Output stream to write file

            OutputStream output = new FileOutputStream(fileName,false);
            byte data[] = new byte[1024];

            System.out.println("Downloading");
            long total = 0;
            while ((count = input.read(data)) != -1) {
            total += count;

            // writing data to file
            output.write(data, 0, count);
        }
            // flushing output
            output.flush();
            // closing streams
            output.close();
            input.close();
        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }
        return null;
    }

谢谢。

不想用多余的代码轰炸。如果需要其他代码,我很乐意提供。

2 个答案:

答案 0 :(得分:0)

您的根错误

String root = "data/data/package.appname";

确保您的根目录包含正确的软件包名称或文件路径。

程序包名称,应为您的应用程序ID

答案 1 :(得分:0)

更新后的答案

这对我有用,将文件写入本地存储,然后在方法PostExecute上再次读取

class DownloadJSON extends AsyncTask<String, Void, Void>{

        String fileName;
        String responseTxt;
        String inputLine;
        String folder;

        @Override
        protected Void doInBackground(String... strings) {
            try {
                String root = "data/data/com.example.jsonapp2";
                URL url = new URL(strings[0]);
                HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
                //Set methods and timeouts
                urlConnection.setRequestMethod("GET");
                urlConnection.setReadTimeout(15000);
                urlConnection.setConnectTimeout(15000);

                urlConnection.connect();

                //Create a new InputStreamReader
                InputStreamReader streamReader = new
                        InputStreamReader(urlConnection.getInputStream());
                BufferedReader reader = new BufferedReader(streamReader);

                StringBuilder response  = new StringBuilder();

                //Check if the line we are reading is not null
                while((inputLine = reader.readLine()) != null){
                    response.append(inputLine);
                }

                //Close our InputStream and Buffered reader
                reader.close();
                streamReader.close();

                responseTxt = response.toString();

                Log.d(TAG, "doInBackground: responseText " + responseTxt);

                // PREPARE FOR WRITE FILE TO DEVICE DIRECTORY
                FileOutputStream fos = null;
                fileName = "fileName.json";
                folder = fileFolderDirectory();

                try {
                    fos = new FileOutputStream(new File(folder + fileName));
                    //fos = openFileOutput(folder + fileName, MODE_PRIVATE);
                    fos.write(responseTxt.getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if(fos != null){
                        fos.close();
                    }
                }


            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            // -- THIS METHOD IS USED TO ENSURE YOUR FILE AVAILABLE INSIDE LOCAL DIRECTORY -- //

            FileInputStream fis = null;
            try {
                fis = new FileInputStream(new File(folder +fileName));
                InputStreamReader isr = new InputStreamReader(fis);
                BufferedReader br = new BufferedReader(isr);
                StringBuilder sb = new StringBuilder();
                String text;

                while ((text = br.readLine()) != null) {
                    sb.append(text).append("\n");
                }

                Toast.makeText(TestActivity.this, "result " + sb.toString(), Toast.LENGTH_SHORT).show();

            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

糟糕,几乎忘记了这种方法

public static String fileFolderDirectory() {
        String folder = Environment.getExternalStorageDirectory() + File.separator + "write_your_app_name" + File.separator;
        File directory = new File(folder);
        if(!directory.exists()){
            directory.mkdirs();
        }
        return folder;
    }