【问题标题】:convert PDF file to byte array in android在android中将PDF文件转换为字节数组
【发布时间】:2019-09-03 06:17:42
【问题描述】:

我想在 (onActivityResult) 中将 PDF 文件转换为字节数组 我尝试了几种不同的方法,但没有奏效 有知道的请回答。

更新:

  case 1212 :
                    if (resultCode == RESULT_OK){
                        Uri uri = data.getData();
                        File file = new File(uri.getPath());
                        int size = (int) file.length();
                        byte[] bytes = new byte[size];
                        try {
                            BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
                            buf.read(bytes, 0, bytes.length);
                            buf.close();
                        } catch (FileNotFoundException e) {
                           Toast.makeText(getApplicationContext(),"FileNotFound",Toast.LENGTH_LONG).show();
                            e.printStackTrace();
                        } catch (IOException e) {
                            Toast.makeText(getApplicationContext(),"IOException",Toast.LENGTH_LONG).show();
                            e.printStackTrace();
                        }

                    }else Toast.makeText(getApplicationContext(),"خطا!",Toast.LENGTH_LONG).show();

此代码显示 FileNotFound Toast

【问题讨论】:

  • 您为什么要这样做?如果您的 pdf 文件长度为 10 或 100 MB,该怎么办?
  • uri.getPath() 通常不会返回文件路径。使用developer.android.com/reference/android/content/…从Uri打开流,然后读入字节数组。
  • but it didn't work 究竟如何?

标签: java android file pdf


【解决方案1】:

使用来自 java 7 的包 java.nio.file

Path pdfFilePath = Paths.get("/file/path/your_file.pdf"); //File path
byte[] pdfByteArray = Files.readAllBytes(pdfFilePath );

【讨论】:

    猜你喜欢
    • 2016-04-14
    • 2012-01-28
    • 2015-09-16
    • 1970-01-01
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    • 2020-09-04
    相关资源
    最近更新 更多