【发布时间】:2019-11-08 17:00:22
【问题描述】:
我在我的 Java 应用程序中使用 jSerialComm 从 Arduino 接收数据。但是,Java 程序只读取传入的“字节”。这不好,因为我的 Arduino 正在打印一个长字符串,我希望 Java 应用程序读取整个字符串而不会丢失任何信息。我的 Arduino 每秒发送两次数据字符串。
我在带有 JDK 13 的 Windows 10 上,使用 IntelliJ、Adruino IDE 1.8.10。
目前字符串很长,可能会改变大小,所以我不能只读取一定数量的字节。
我什至目前正在打印前面带有 # 且末尾带有 * 的字符串。我的设计目前正在以某种方式丢失数据,只收到一个可接受的字符串,可能是 10 个字符串中的 1 个。
byte[] newData = new byte[comPort.bytesAvailable(0];
int numRead = comPort.readBytes(newData, newData.length);
stringBuffer = new String(newData,0,numRead);
if (stringBuffer.startsWith("#"))
{
serialString+=stringBuffer;
while (!stringBuffer.endsWith("*")
{
numRead = comPort.readBytes(newData, newData.length);
stringBuffer = new String(newData,0,numRead);
serialString+=stringBuffer;
}
//double check it is the proper format
if (serialString.startsWith("#") && serial.String.endsWith("*")
{
//do stuff
}
serialString = "";
}
除了 readBytes() 之外还有什么方法可以使用吗?我知道我可以使用 getInputStream(),但我不确定从那里去哪里。
非常感谢您。
【问题讨论】:
-
分配一个固定大小的缓冲区 (
newData)。一开始可能有 0 个字节可用 -
@Juraj 感谢您的回复。我正在查找缓冲区,但我不确定它们是如何使用的,尤其是在这种情况下。我需要什么样的缓冲区?缓冲输入流?谢谢!
-
byte[] newData = new byte[64]; -
@Juraj 我很惊讶,如果我将其更改为硬编码数字,它似乎永远不会得到正确的字符串。
-
打印 stringBuffer 以查看收到的内容