来自Com端口的Java readLine
有没有办法将这个java代码(从com端口读取)更改为读取行来自Com端口的Java readLine,java,serial-port,rxtx,Java,Serial Port,Rxtx,有没有办法将这个java代码(从com端口读取)更改为读取行 例如 我正在使用rxtx com 原始方法: public void serialEvent(SerialPortEvent event) { switch (event.getEventType()) { case SerialPortEvent.DATA_AVAILABLE: byte[] readBuffer = new byte[10]; int numB
例如
我正在使用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
,您可以用一个和一个(有一个)来包装它。大概
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();
}
}
或者你可以用
您可以使用一个缓冲的inputstream来包装读取器,读取器可以包装您的inputstream。。。类似于BufferedReader br=新的BufferedReader(新的InputStreamReader(即“UTF-8”);(其中“is”是您的输入流。请阅读Java IO
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();
}