首页 > 解决方案 > 成功将文件写入磁盘存储后如何打开文件

问题描述

所以我有这种方法可以从我的服务器写入写入存储的响应结果。

private boolean writeResponseBodyToDisk(ResponseBody body) {
        try {
            File filesDir = getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
            assert filesDir != null;

            downloadedFile = new File(filesDir,
                    "file_name" + ".pdf");

            InputStream inputStream = null;
            OutputStream outputStream = null;

            try {
                byte[] fileReader = new byte[4096];

                long fileSize = body.contentLength();
                long fileSizeDownloaded = 0;

                inputStream = body.byteStream();
                outputStream = new FileOutputStream(downloadedFile);

                while (true) {
                    int read = inputStream.read(fileReader);

                    if (read == -1) {
                        break;
                    }

                    outputStream.write(fileReader, 0, read);

                    fileSizeDownloaded += read;
                }

                outputStream.flush();

                // This is how i call openPDF() method
                openPDF(Uri.fromFile(downloadedFile));

                return true;
            } catch (IOException e) {
                return false;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }

                if (outputStream != null) {
                    outputStream.close();
                }
            }
        } catch (IOException e) {
            return false;
        }
    }

但是如何在成功写入磁盘存储后立即打开这个文件呢?我已尝试阅读标题为“访问共享存储中的文档和其他文件”和“访问特定于应用程序的文件”的文档,但解释并没有导致我需要的信息。

根据我的阅读,我认为从不同的 android 版本访问存储需要一个差异化因素,比如

 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
     // only for gingerbread and newer versions
 }

我试过这个方法,但它不起作用..

    private void openPDF(Uri uri) {
        try {
            Intent testIntent = new Intent("com.adobe.reader");
            testIntent.setType("application/pdf");
            testIntent.setAction(Intent.ACTION_VIEW);
            Uri uri = Uri.fromFile(uri);
            testIntent.setDataAndType(uri, "application/pdf");
            startActivity(testIntent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

标签: android

解决方案


推荐阅读