Android : How to read file in bytes?

前端 未结 8 1038
逝去的感伤
逝去的感伤 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

    Here is a solution that guarantees entire file will be read, that requires no libraries and is efficient:

    byte[] fullyReadFileToBytes(File f) throws IOException {
        int size = (int) f.length();
        byte bytes[] = new byte[size];
        byte tmpBuff[] = new byte[size];
        FileInputStream fis= new FileInputStream(f);;
        try {
    
            int read = fis.read(bytes, 0, size);
            if (read < size) {
                int remain = size - read;
                while (remain > 0) {
                    read = fis.read(tmpBuff, 0, remain);
                    System.arraycopy(tmpBuff, 0, bytes, size - remain, read);
                    remain -= read;
                }
            }
        }  catch (IOException e){
            throw e;
        } finally {
            fis.close();
        }
    
        return bytes;
    }
    

    NOTE: it assumes file size is less than MAX_INT bytes, you can add handling for that if you want.

提交回复
热议问题