FileInputStream to byte array in Android application

前端 未结 4 1223
梦如初夏
梦如初夏 2020-12-17 16:00

I have a FileInputStream created using Context.openFileInput(). I now want to convert the file into a byte array.

Unfortunately, I can\'t determine the

相关标签:
4条回答
  • 2020-12-17 16:10

    This should work.

    InputStream is = Context.openFileInput(someFileName);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] b = new byte[1024];
    while ((int bytesRead = is.read(b)) != -1) {
       bos.write(b, 0, bytesRead);
    }
    byte[] bytes = bos.toByteArray();
    
    0 讨论(0)
  • 2020-12-17 16:15

    You can pre-allocate the byte array using

    int size = context.getFileStreamPath(filename).length();
    

    This way, you will avoid allocating memory chunks every time your ByteArrayOutputStream fills up.

    0 讨论(0)
  • 2020-12-17 16:21

    For the method to work on any device and aplication you just need to replace:

    InputStream is = Context.getContentResolver().openInputStream(yourFileURi);
    

    This way you can encode external files as well.

    0 讨论(0)
  • 2020-12-17 16:28

    This is the easiest way

    FileInputStream fis =  openFileInput(fileName);
    
    byte[] buffer =   new byte[(int) fis.getChannel().size()];
    
    fis.read(buffer);
    
    0 讨论(0)
提交回复
热议问题