OkHttp возвращает IOException, когда createNewFile вызывается внутри onResponse - PullRequest
0 голосов
/ 29 апреля 2020

Я пытаюсь загрузить PDF-файл в папке с данными Android. Но когда я вызываю метод createNewFile, приложение создает sh с IOException.

D/OkHttp: Callback failure for call to https://www...
D/OkHttp: java.io.IOException: No such file or directory
D/OkHttp:     at java.io.UnixFileSystem.createFileExclusively0(Native Method)
D/OkHttp:     at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:317)
D/OkHttp:     at java.io.File.createNewFile(File.java:1008)
D/OkHttp:     at com.meidio.common.manager.FileManager$2.onResponse(FileManager.java:118)
D/OkHttp:     at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:504)
D/OkHttp:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
D/OkHttp:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
D/OkHttp:     at java.lang.Thread.run(Thread.java:919)

Я делаю следующее по onResponse:

public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
        if (response.isSuccessful()) {
            String contentType = response.body().contentType().toString();
            File folder = new File(Environment.getExternalStorageDirectory(), "/Meidio");

            if (!folder.exists()) {
                boolean folderCreated = folder.mkdir();
            }

            File file = new File(folder.getPath() + "/document.pdf");
            if (file.exists()) {
                boolean fileDeleted = file.delete();
                LoggerManager.handlesDebug("openPdfFromUrl", "File deleted: " + fileDeleted + "");
            }

            //Create New File if not present
            boolean fileCreated = false;

            if (!file.exists()) {
                file.getParentFile().mkdirs();

                fileCreated = file.createNewFile();
            }

            Uri uriCreated;
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uriCreated = FileProvider.getUriForFile(MDApplication.getCurrentAppContext().getApplicationContext(), MDApplication.getCurrentAppContext().getApplicationContext().getPackageName() + ".provider", file);
            } else {
                uriCreated = Uri.fromFile(file);
            }

            BufferedSink sink = Okio.buffer(Okio.sink(file));
            sink.writeAll(response.body().source());
            sink.close();

            if (fileCreated) {
                Intent target = new Intent(Intent.ACTION_VIEW);
                target.setData(uriCreated);
                target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | FLAG_GRANT_READ_URI_PERMISSION | FLAG_GRANT_WRITE_URI_PERMISSION);
                context.startActivity(target);
                BusProvider.getInstance().post(new ShowHideLoadingEvent(false, false)); // Loading Dismiss
                LoggerManager.handlesDebug("openPdfFromUrl", "Response OK");
            } else {
                LoggerManager.handlesDebug("openPdfFromUrl", "Response OK, but file not created!");
            }

        }

Путь провайдера xml имеет следующее:

<?xml version="1.0" encoding="utf-8"?><!--
<paths xmlns:android="http://schemas.android.com/apk/res/android">

    <external-path
        name="files_root"
        path="Android/data/${applicationId}" />
    <external-path
        name="external_files"
        path="." />
    <external-path
        name="/storage/emulated/0"
        path="." />
    <external-files-path
        name="documents"
        path="/Meidio" />
    <files-path
        name="app_contact_photos"
        path="app_contact_photos" />

    <cache-path name="cache" path="." />
    <external-path name="external" path="." />

    <root-path name="root" path="." />
    <files-path name="contact_photos" path="/" />
    <files-path name="contact_photos" path="app_contact_photos/"/>
    <files-path name="files" path="." />

    <external-cache-path name="external_cache" path="." />

    <external-cache-path
        name="cache"
        path="camera" />

</paths>

Я не знаю, в чем заключается ошибка, файл, который пытается создать, является следующим /storage/emulated/0/meidio/document.pdf. Итак, я немного растерялся.

Несколько советов?

...