Android : How to read file in bytes?

前端 未结 8 1007
逝去的感伤
逝去的感伤 2020-11-27 15:25

I am trying to get file content in bytes in Android application. I have get the file in SD card now want to get the selected file in bytes. I googled but no such success. Pl

8条回答
  •  死守一世寂寞
    2020-11-27 15:35

    If you want to use a the openFileInput method from a Context for this, you can use the following code.

    This will create a BufferArrayOutputStream and append each byte as it's read from the file to it.

    /**
     * 

    * Creates a InputStream for a file using the specified Context * and returns the Bytes read from the file. *

    * * @param context The context to use. * @param file The file to read from. * @return The array of bytes read from the file, or null if no file was found. */ public static byte[] read(Context context, String file) throws IOException { byte[] ret = null; if (context != null) { try { InputStream inputStream = context.openFileInput(file); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); int nextByte = inputStream.read(); while (nextByte != -1) { outputStream.write(nextByte); nextByte = inputStream.read(); } ret = outputStream.toByteArray(); } catch (FileNotFoundException ignored) { } } return ret; }

提交回复
热议问题