0

次のコードを含む PDF ファイルをダウンロードしようとしています。

 try {
                URL url = new URL(urls[0]);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.connect();

                if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    return "Server returned HTTP " + conn.getResponseCode() + " "
                            + conn.getResponseMessage();
                }

                //Useful to display progress
                int fileLength = conn.getContentLength();


                //Download the mFile
                InputStream input = new BufferedInputStream(conn.getInputStream());


                //Create a temp file cf. https://developer.android.com/training/data-storage/files.html
//                mFile = File.createTempFile(FILENAME, "pdf", mContext.getCacheDir());
                mFile = new File(getFilesDir(), "temp.pdf");
                FileOutputStream fos = openFileOutput("temp.pdf",MODE_PRIVATE);




                byte[] buffer = new byte[10240];
                long total = 0;
                int count;
                while ((count = input.read(buffer)) != -1) {
                    if (isCancelled()) {
                        input.close();
                        return null;
                    }
                    total += count;

                    //Publish the progress
                    if (fileLength > 0) {
                        publishProgress((int) (total * 100 / fileLength));
                    }
                    fos.write(buffer);

                }
                Log.i(LOG_TAG, "File path: " + mFile.getPath());



                fos.flush();
                fos.close();
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

次に、ダウンロードしたファイルを PdfRenderer を使用してレンダリングします。上記のコードを使用して作成された File オブジェクトを PdfRenderer クラスから ParcelFileDescriptor.open() に渡すたびに、「例外: ファイルが PDF 形式ではないか破損しています」というメッセージが表示されます。
レンダリング コードは、受信した File オブジェクトに対して次の処理を行い、PdfRenderer を作成します。

 mFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
            // This is the PdfRenderer we use to render the PDF.
            mPdfRenderer = new PdfRenderer(mFileDescriptor);

どうすればこれを解決できますか? createTempFile を使用して一時ファイルを作成したり、多くの StackOverFlow 投稿を作成したりするなど、多くのオプションを試しましたが、すべて失敗しました。私の問題の原因を誰か知っていますか?

4

1 に答える 1

0

まず、Android でファイルを作成し、そのファイルへの出力ファイル ストリームを開く必要があります。

        mFile = new File(getFilesDir(), "temp.pdf");
        FileOutputStream fos = openFileOutput("temp.pdf",MODE_PRIVATE);

次に、出力ストリームへの書き込み時に回避したい、かなり一般的な Java の不具合があります (この投稿の厚意による)。ストリーム ライターを次のように変更します。

            fos.write(buffer, 0, count);
于 2017-12-24T17:56:08.887 に答える