Android |如何读取文件到字节数组? [英] Android | How Read file to byte array?

查看:248
本文介绍了Android |如何读取文件到字节数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将文件从手机发送到我的设备(机载HC-06).但是我需要部分发送.我如何读取文件到字节数组?我有自己的传输协议..

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..

推荐答案

要阅读File,最好搭配FileInputStream使用.

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

您创建一个File对象,该对象指向设备上的文件.用File作为参数打开FileInputStream.

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

您创建一个byte[]的缓冲区.在这里,您将逐块读取文件.

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

您使用read(buffer)一次读取了一个块.到达文件末尾时,它将返回-1.在此循环中,您必须在缓冲区上进行工作.在您的情况下,您将希望使用协议发送它.

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.

请勿尝试一次读取整个文件,否则您可能会得到OutOfMemoryError.

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) {
    }
}

这篇关于Android |如何读取文件到字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆