Programming Tutorials

Sample Java program shows how to read from COM port using Java

By: Johanes in Java Tutorials on 2007-08-21  

This Sample Java program shows how to read from COM port using Java.

If you are one of those living still in the 20th century then your JDK probably doesn't come with the Java COMM API. So you would have to download the Java Comm Api from On the other hand if you are using one of the later versions of JDK then the Java Comm API should be inbuilt together with your JDK. Once you have this then create a sample program to read from the PC's COM port. And then copy and paste the below code into that program. Compile and run it. If the compilation fails then it is probably due to some classpath problem. You will have to add the javax.comm api to your classpath properly.

import java.util.*;
import javax.comm.*;

public class SimpleRead implements Runnable, SerialPortEventListener {
    static CommPortIdentifier portId;
    static Enumeration portList;

    InputStream inputStream;
    SerialPort serialPort;
    Thread readThread;

    public static void main(String[] args) {
        portList = CommPortIdentifier.getPortIdentifiers();

        while (portList.hasMoreElements()) {
            portId = (CommPortIdentifier) portList.nextElement();
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                 if (portId.getName().equals("COM1")) {
                //if (portId.getName().equals("/dev/term/a")) {
                    SimpleRead reader = new SimpleRead();

    public SimpleRead() {
        try {
            serialPort = (SerialPort)"SimpleReadApp", 2000);
        } catch (PortInUseException e) {}
        try {
            inputStream = serialPort.getInputStream();
        } catch (IOException e) {}
	try {
	} catch (TooManyListenersException e) {}
        try {
        } catch (UnsupportedCommOperationException e) {}
        readThread = new Thread(this);

    public void run() {
        try {
        } catch (InterruptedException e) {}

    public void serialEvent(SerialPortEvent event) {
        switch(event.getEventType()) {
        case SerialPortEvent.BI:
        case SerialPortEvent.OE:
        case SerialPortEvent.FE:
        case SerialPortEvent.PE:
        case SerialPortEvent.CD:
        case SerialPortEvent.CTS:
        case SerialPortEvent.DSR:
        case SerialPortEvent.RI:
        case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
        case SerialPortEvent.DATA_AVAILABLE:
            byte[] readBuffer = new byte[20];

            try {
                while (inputStream.available() > 0) {
                    int numBytes =;
                System.out.print(new String(readBuffer));
            } catch (IOException e) {}

Add Comment

* Required information


No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)