Dmitry Lyalin Dmitry Lyalin - 3 years ago 275
Android Question

Android | How Read file to byte array?

I need to sent file from phone to my device (HC-06 on board). But i need to send it part by part. How i can read file to byte array? I have my own transfer protocol..

Answer Source

To read a File you would be best served with a FileInputStream.

You create a File object pointed to your file on the device. You open the FileInputStream with the File as a parameter.

You create a buffer of byte[]. This is where you will read your file in, chunk by chunk.

You read in a chunk at a time with read(buffer). This returns -1 when the end of the file has been reached. Within this loop you must do the work on your buffer. In your case, you will want to send it using your protocol.

Do not try to read the entire file at once otherwise you will likely get an OutOfMemoryError.

File file = new File("input.bin");
FileInputStream fis = null;
try {
    fis = new FileInputStream(file);

    byte buffer[] = new byte[4096];
    int read = 0;

    while((read = fis.read(buffer)) != -1) {
        // Do what you want with the buffer of bytes here.
        // Make sure you only work with bytes 0 - read.
        // Sending it with your protocol for example.
    }
} catch (FileNotFoundException e) {
    System.out.println("File not found: " + e.toString());
} catch (IOException e) {
    System.out.println("Exception reading file: " + e.toString());
} finally {
    try {
        if (fis != null) {
            fis.close();
        }
    } catch (IOException ignored) {
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download