2017-04-18 29 views
0

我有問題從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! 
+0

它爲什麼要做其他事情?你將'fullLine'設置爲一個空白字符,然後從流中讀取一個字符,然後執行'System.out.println(fullLine)'。如果你想讀一整行文本,爲什麼不創建一個'BufferedReader'並且在其上調用'readLine()'? –

回答

0

從流中讀取一行文本的常用方法是使用BufferedReader中的readLine()方法。是否有任何理由,你不能這樣做:

BufferedReader reader = new BufferedReader(new InputStreamReader(input)); 

// ... 

String fullLine = reader.readLine(); 
System.out.println(fullLine); 

而不是試圖一次讀取一個字節(和基本上重新發明車輪)。

+0

謝謝,我不知道這一點。我正在研究其他一些我在線閱讀的例子。 –

0

(byte)input.read()讀取單個字節,並System.out.println(fullLine)打印這個人物並在此之後新增一行。所以代碼工作。嘗試使用System.out.print(fullLine)代替。