【问题标题】:I'm confused about PDF files我对 PDF 文件感到困惑
【发布时间】:2020-02-25 12:16:22
【问题描述】:

如果我以这种方式使用我的代码,PDF 说它是无效的并且无法打开,但是如果我交换它们并且在 A 之前有 B,它可以正常工作吗?为什么会这样,我该怎么做才能让它工作? TIA

    InputStream in = new BufferedInputStream(conn.getInputStream());
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));

//A
    String line = "";
                StringBuilder builder = new StringBuilder();
                try {
                    while ((line = reader.readLine()) != null) {
                        builder.append(line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

//B
    File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            File outputFile = new File(directory, "goo.pdf");
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(outputFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            byte[] buffer = new byte[1024];
            int len1 = 0;//init length
            while (true) {
                try {
                    if (!((len1 = in.read(buffer)) != -1)) break;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    fos.write(buffer, 0, len1);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

【问题讨论】:

  • 你永远不会关闭你的FileOutputStream。简单地具有 A 的时间延迟可能会导致一些内部缓冲区被刷新。
  • 感谢您的建议。我最后关闭了 FileOutputStream,我仍然得到相同的结果。
  • 什么是stream
  • 刚刚更正了。 'stream' 应该是 'in'。
  • 现在这是一个非常重要的细节,因为没有它,这两个部分看起来完全不相关。请通过此示例了解发布您正在执行的实际代码而不只是近似值的重要性。

标签: java android pdf


【解决方案1】:

一个 InputStream 只能读取一次。

在“A”中,读取流并将内容放入 StringBuilder。
在“B”中,流(现在为空)被读取并通过管道传输到文件。
有了 A,输出文件将始终为空。

只需删除 A,因为它在这里没有为您做任何事情。

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多