在Android中,将文件转换为字节数组始终为null

时间:2016-08-19 10:00:16

标签: android arrays file

我正在开发一款Android应用。在我的应用程序中,我需要将文件转换为字节数组。我尝试了Stack Overflow解决方案,它总是给我null。请参阅下面的代码。

这是我的onActivityResult回调

        Uri bookUri = data.getData();
        if(bookUri!=null)
        {
            String filePath = bookUri.toString();
            String mime = app.getMimeType(filePath);
            if(mime!=null && !mime.isEmpty() && (mime.toLowerCase()=="application/pdf" || mime.toLowerCase()=="application/txt" || mime.toLowerCase()=="application/text"))
            {
                bookFile = new File(filePath);
                if(bookFile!=null)
                {
                    byte[] bookByteArray = app.convertFileToByteArray(bookFile); //Converting file to byte array here
                    if(bookByteArray==null)
                    {

                        Toast.makeText(getBaseContext(),"NULL",Toast.LENGTH_SHORT).show();
                    }

                }
                //change book cover image
                ivBookFile.setImageResource(R.drawable.book_selected);
            }
            else{
                Toast.makeText(getBaseContext(),"Unable to process file you have chosen.",Toast.LENGTH_SHORT).show();
            }
        }

我评论了上面代码中我将文件转换为字节数组的位置。上面的代码总是烘烤“NULL”消息。

这是我的转换方法

public byte[] convertFileToByteArray(File file)
    {
        FileInputStream fileInputStream=null;

        byte[] bFile = new byte[(int) file.length()];

        try {
            //convert file into array of bytes
            fileInputStream = new FileInputStream(file);
            fileInputStream.read(bFile);
            fileInputStream.close();

            return bFile;
        }catch(Exception e){
           return null;
        }
    }

为什么它总是为空?如何在Android中正确地将文件转换为字节数组?

1 个答案:

答案 0 :(得分:0)

 public static byte[] readBytes(InputStream inputStream) throws IOException {
    byte[] b = new byte[1024];
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    int c;
    while ((c = inputStream.read(b)) != -1) {
      os.write(b, 0, c);
    }
    return os.toByteArray();
  }