我需要将文件从手机发送到我的设备(机载 HC-06)。但我需要部分发送。我如何将文件读取到字节数组?我有自己的传输协议..
要阅读 a,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) {
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5060 次 |
| 最近记录: |