Android |如何将文件读取到字节数组?

时间:2016-03-11 11:49:22

标签: android bluetooth

我需要将文件从手机发送到我的设备(船上的HC-06)。但我需要逐个发送它。我如何读取文件到字节数组?我有自己的转让协议..

2 个答案:

答案 0 :(得分:1)

要阅读File,您最好使用FileInputStream

您在设备上创建指向文件的File对象。您以FileInputStream作为参数打开File

您创建byte[]的缓冲区。在这里你将读取你的文件,块大块。

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

请勿尝试一次阅读整个文件,否则您可能会获得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) {
    }
}

答案 1 :(得分:0)

这个代码对我有用,在一个Android项目中,所以希望它能为你工作。

byte[] fileContent = getByte(path); // call the method from there....


     private byte[] getByte(String path) {
        byte[] getBytes = {};
        try {
            File file = new File(path);
            getBytes = new byte[(int) file.length()];
            InputStream is = new FileInputStream(file);
            is.read(getBytes);
            is.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return getBytes;
    }
相关问题