有没有更快的方法将字节从一个数组复制到另一个数组而无需迭代?
我正在通过蓝牙从输入流中读取字节
public void run() {
byte[] buffer = new byte[100]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
break;
}
}
}
这会向处理程序发送一个随机数的字节。 然后我读取这些并将它们放入一个数组中,然后在下载完成时处理数据。从 PIC micro 发送的数据是 6055 字节长。
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case SUCCESS_CONNECT:
// Connected so start connected thread
btSocket = (BluetoothSocket) msg.obj;
byteCount = 0;
arrayCount = 0;
mConnectedThread = new FullDataActivity.ConnectedThread(btSocket);
mConnectedThread.start();
mConnectedThread.write(getFullDataConByte); // Send 255 to start
break;
case RECIEVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
// iterate through obj and copy bytes to fullDataChunk array
for (int a = 0; a < msg.arg1; a++) {
fullDataChunk[byteCount] = readBuf[a];
Log.d("readBuf[a] = ",Integer.toString(readBuf[a] & 0xFF));
byteCount++;
}
// if all bytes done process
if (byteCount == 6055) {// process data when complete.
我的处理程序在某处丢失字节并在 for 循环中复制它们时损坏数据。我不知道 run 方法是否在 for 循环中处理其余字节之前向处理程序发送新字节。 我已经完成了运行中发送的字节的日志,它们是正确的。正是当处理程序正在处理时,它们才会出错。
我需要确保发送的数据在发送新数据之前得到处理,或者更快地将数据复制到数组? 任何人有任何想法。
最佳答案
复制数组的最快方法应该是使用 System.arraycopy() .
关于java - 将字节从一个数组复制到另一个数组而无需在 Java 中进行迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39775898/