2

is any way to change this java code (read from com port) to read lines ?
eg.

I'm using rxtx com

original method:

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));
    }
}
1
  • 1
    You could use a buffered inputstream which wraps a reader which can wrap your inputstream ... like BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); (Where "is" is your inputstream. Read up on Java IO Commented Aug 12, 2014 at 17:07

1 Answer 1

1

Assuming inputStream is an InputStream, you could wrap it with an InputStreamReader and wrap that with a BufferedReader (that has a readLine()). Something like,

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();
    }
  }

or you could possible use with 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();
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.