gpt4 book ai didi

来自 Com 端口的 Java readLine

转载 作者:行者123 更新时间:2023-11-30 09:04:21 25 4
gpt4 key购买 nike

有什么方法可以改变这个 java 代码(从 com 端口读取)以读取行?
例如。

我正在使用 rxtx com

原始方法:

public void serialEvent(SerialPortEvent event) {
switch (event.getEventType()) {
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[10];
int numBytes = 0;
try {
while (inputStream.available() > 0) {
numBytes = inputStream.read(readBuffer);
}
} catch (IOException e) {
System.out.println(e);
}
System.out.println(Arrays.toString(readBuffer));
}
}

最佳答案

假设 inputStream 是一个 InputStream,你可以用 InputStreamReader 包装它并用 BufferedReader 包裹起来(有一个 readLine() )。类似的东西,

case SerialPortEvent.DATA_AVAILABLE:
String line;
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}

或者您可以使用 try-with-resouces ,

case SerialPortEvent.DATA_AVAILABLE:
String line;
BufferedReader br = null;
try (br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));) {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}

关于来自 Com 端口的 Java readLine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25270025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com