我有問題從COM端口讀取東西,我在JavaFX應用程序中使用txrx庫。下面的代碼顯示它的閱讀:從InputStream顯示整行
public void serialEvent(SerialPortEvent evt) {
String bytesin = null;
String fullLine = " ";
if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE)
{
try
{
byte singleData = (byte)input.read();
if (singleData != CR_ASCII)
{
bytesin = new String(new byte[] {singleData});
fullLine = fullLine+bytesin;
System.out.println(fullLine);
}
else if (singleData == CR_ASCII)
{
System.out.println("CR detected!");
}
else
{
statusLabel.setText("Read!");
}
}
catch (Exception e)
{
statusLabel.setText("Failed to read data. (" + e.toString() + ")");
System.out.println("Failed to read data. (" + e.toString() + ")");
}
}
}
==與該代碼的問題是,它顯示在每行的單個字符的一切。 我的USB設備輸出以下文本(個字符是ASCII,而不是字符):
**T-Pod-1Ch**(Char 13)(Char 10)
但是我的代碼輸出給出了這樣的:
*
*
T
-
P
o
d
-
1
C
h
*
*
CR detected!
*
*
T
-
P
o
d
-
1
C
h
*
*
CR detected!
它爲什麼要做其他事情?你將'fullLine'設置爲一個空白字符,然後從流中讀取一個字符,然後執行'System.out.println(fullLine)'。如果你想讀一整行文本,爲什麼不創建一個'BufferedReader'並且在其上調用'readLine()'? –