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

By: Johanes Emailed: 1643 times Printed: 2109 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

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) {}

Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.

Bookmark and Share


1. View Comment

i am getting an exceptions... pls help me..

Exception in thread "Thread-0" java.lang.ExceptionInInitializerError
at sms.Sender.send(
Caused by: java.lang.RuntimeException: Uncompilable source code - cannot find symbol
symbol: class SerialPortEventListener
at sms.SerialConnection.<clinit>(
... 3 more

View Tutorial          By: FEBI at 2014-03-08 06:01:44

Your name (required):

Your email(required, will not be shown to the public):

Your sites URL (optional):

Your comments:

More Tutorials by Johanes
Sample Java program shows how to write to COM port using Java.
Sample Java program shows how to read from COM port using Java

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
How to Send SMS using Java Program (full code sample included)
InetAddress Example program in Java
XML and Java - Parsing XML using Java Tutorial
Read from a COM port using Java program
wait(), notify() and notifyAll() in Java - A tutorial
Student marks calculation program in Java
How to use Iterator in Java
Recursion in java
Using StringTokenizer in Java
Vector example in Java
Integer: byte, short, int, and long data types in Java
TCP Server and TCP Client in Java
Count number of vowels, consonants and digits in a String in Java
indexOf( ) and lastIndexOf( ) in Java
Method Overloading (function overloading) in Java
Most Emailed Articles (in Java)
What is Multithreaded programming?
TCP Server and TCP Client in Java
setPriority() and getPriority() in Java
Using One-Dimensional Arrays in Java
Read from a COM port using Java program
Type Casting in Java
Simple Port Scanner application using Java
constants and variables
Update contents of a file within a jar file
HTTPS Java - URL Connection program. Using HttpsURLConnection
Major components of FxObjects in JavaFX
Java program for Associate keys with values
How to use set, get basic and nested properties for Spring framework
How to reverse the elements in a Single dimension array and display the output
Of Object, equals (), == and hashCode ()