0

Цель: скачать файл и сохранить в папке Downloads
При попытке открыть файл для записи таким способом

FileOutputStream output = openFileOutput(folder + "/" + name_pic, Context.MODE_PRIVATE);

Выдаёт мне такую ошибку:
E/Error:: File /storage/emulated/0/Download/picture.png contains a path separator
Как исправить? Вызываю класс так:

String url = "http://192.168.1.7/static/picture.png"; 
new DownloadFileFromURL().execute(url);

В манифесте прописаны права для INTERNET,WRITE_EXTERNAL_STORAGE и READ_EXTERNAL_STORAGE
За помощь буду очень благодарен

@SuppressLint("StaticFieldLeak")
class DownloadFileFromURL extends AsyncTask<String, String, String> {
    /**
     * Downloading file in background thread
     * */
    @Override
    protected String doInBackground(String... f_url) {
        int count;
        try {
            String root = Environment.getExternalStorageDirectory().toString();
            System.out.println("Downloading");
            URL url = new URL(f_url[0]);
            System.out.println(f_url[0]);
            URLConnection conection = url.openConnection();
            conection.connect();
            int lenghtOfFile = conection.getContentLength();

            InputStream input = new BufferedInputStream(url.openStream(), 8192);

            String folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
            String name_pic = "picture.png";
            //OutputStream output = new FileOutputStream(root+"/downloadedfile.jpg");
            Log.e("Status", "output not opened");
            FileOutputStream output = openFileOutput(folder + "/" + name_pic, Context.MODE_PRIVATE);
            Log.e("Status", "output opened");
            byte data[] = new byte[1024];
            long total = 0;
            while ((count = input.read(data)) != -1) {
                total += count;
                // writing data to file
                output.write(data, 0, count);
                //System.out.println(count);
            }

            // flushing output
            output.flush();

            // closing streams
            output.close();
            input.close();
            Log.e("e", "End");
        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

        return null;
    }
    /**
     * After completing background task
     * **/
    @Override
    protected void onPostExecute(String file_url) {
        System.out.println("Downloaded");
        System.out.println(file_url);
    }

}
2
  • openFileOutput - пишет в приватную папку приложения и принимает только имя файла без подпапок. Вам нужно сделать, как в закомментированной строке new FileOutputStream(folder + "/" + name_pic). И для Android 6.0 и выше разрешения в манифесте недостаточно, нужно ещё запрашивать во время выполнения: Requesting Permissions at Run Time
    – woesss
    4 фев 2018 в 11:52
  • Благодарю!!!! Всё работает
    – ReDen
    4 фев 2018 в 16:06

1 ответ 1

0

Нужно сделать, как в закомментированной строке

new FileOutputStream(folder + "/" + name_pic)

И запросить разрешение во время выполнения

ActivityCompat.requestPermissions(MainActivity.this,
            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
            1);

Спасибо, woesss!

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.