Android : How to read file in bytes?

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

    here it's a simple:

    File file = new File(path);
    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) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    

    Add permission in manifest.xml:

     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    
    0 讨论(0)
  • 2020-11-27 16:00

    Since the accepted BufferedInputStream#read isn't guaranteed to read everything, rather than keeping track of the buffer sizes myself, I used this approach:

        byte bytes[] = new byte[(int) file.length()];
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        DataInputStream dis = new DataInputStream(bis);
        dis.readFully(bytes);
    

    Blocks until a full read is complete, and doesn't require extra imports.

    0 讨论(0)
提交回复
热议问题