1 回答

TA貢獻(xiàn)1845條經(jīng)驗 獲得超8個贊
如果您想編寫僅打印您獲得的字節(jié)的代碼,我會嘗試以下操作:
if (uartDevice != null) {
// Loop until there is no more data in the RX buffer.
try {
byte[] buffer = new byte[CHUNK_SIZE];
int read;
while ((read = uartDevice.read(buffer, buffer.length)) > 0) {
for (int i = 0; i < read; i++) {
System.out.printf("%02x", buffer[i]);
}
}
} catch (IOException e) {
Log.w(TAG, "Unable to transfer data over UART", e);
}
System.out.println(); // Adds a newline after all bytes
}
以下是一個方法,該方法采用 aUartDevice作為參數(shù),從它讀取直到結(jié)束并返回byte包含全部內(nèi)容的單個數(shù)組。不需要保證保存全部內(nèi)容的任意緩沖區(qū)。返回的數(shù)組與它需要的大小完全一樣。僅使用較小的讀取緩沖區(qū)來提高性能。錯誤處理被忽略。
這假設(shè)數(shù)據(jù)不大于內(nèi)存所能容納的大小。
byte[] readFromDevice(UartDevice uartDevice) {
byte[] buffer = new byte[CHUNK_SIZE];
int read;
ByteArrayOutputStream data = new ByteArrayOutputStream();
while ((read = uartDevice.read(buffer, buffer.length)) > 0) {
data.write(buffer, 0, read);
}
return data.toByteArray();
}
當(dāng)所有數(shù)據(jù)都被讀取后,該方法返回,您可以隨意處理返回的數(shù)組。
添加回答
舉報