我正在尝试将byte[]
发送到串口。但是outputstream.write(byte[]);
仅在byte[].length
包含少于100个字节时才有效。
要知道:
byte[]
永远不会包含476个字节以上
此代码有效:
NRSerialPort port = new NRSerialPort(portname, DEFAULTBAUDRATE);
port.connect();
OutputStream outputStream = port.getOutputStream();
for(int i = 0; i<bytes.length; i++){
if(i%10==0){
Thread.sleep(1);
}
outputStream.write(bytes[i]);
}
outputStream.flush();
outputStream.close();
port.disconnect();
优势:适用于所有系统 缺点:可能会不必要地睡觉
这样做:
NRSerialPort port = new NRSerialPort(portname, DEFAULTBAUDRATE);
port.connect();
OutputStream outputStream = port.getOutputStream();
for(byte b : bytes){
outputStream.write(b);
}
outputStream.flush();
outputStream.close();
port.disconnect();
优点:没有不必要的睡眠 缺点:可能无法在快速系统上运行,因为它们可以更快地处理快速系统
但如果字节包含大约100个字节,则下面的代码将失败:
NRSerialPort port = new NRSerialPort(portname, DEFAULTBAUDRATE);
port.connect();
OutputStream outputStream = port.getOutputStream();
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
port.disconnect();
虽然write(byte[])
是sun库中的有效方法
我对此有一些想法:
write(byte[])
未将byte[]
剪切为较小的片段你可能想知道为什么我问这个问题,如果我有一个有效的解决方案。良好:
我想知道我的哪个解决方案更好和/或是否有其他/更好的方法来做到这一点。除了为什么要使用方法write(byte[])
,如果它的处理能力依赖于硬件(至少在JavaDoc中这样说呢?)
答案 0 :(得分:0)
假设我已经使用Google搜索了正确的代码,这看起来不像Java的问题,而是NRSerialPort
库的实现。
深入了解代码,我可以看到SerialOutputStream提供了OutputStream
的实现,并根据write(byte)
或write(byte[])
方法是否调用了两种不同的方法使用:
请参阅here
protected native void writeByte( int b, boolean i ) throws IOException;
protected native void writeArray( byte b[], int off, int len, boolean i )
throws IOException;
如果不深入研究本机代码,我会猜测writeArray
方法的实现可能存在错误。