Read from a COM port using Java program

By: Steven Lim Emailed: 1614 times Printed: 2079 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

Most projects that deal with hardware and devices, needs to communicate with them using the COM port of the PC or Server. For example if there is a modem that is connected to a server via its COM port and the Java program has to read the output of the modem then the Java program has to read the COM port for any incoming data.

This sample Java program can be used to Read from a COM port for incoming data and process it. Note that you will need to change the Port number to COM1 or COM2 or any other ports as required.

Also if you are using unix based machines then you will have to uncomment the /dev/term/a instead of COM.

import java.io.*;
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) portId.open("SimpleReadApp", 2000);
        } catch (PortInUseException e) {System.out.println(e);}
        try {
            inputStream = serialPort.getInputStream();
        } catch (IOException e) {System.out.println(e);}
	try {
            serialPort.addEventListener(this);
	} catch (TooManyListenersException e) {System.out.println(e);}
        serialPort.notifyOnDataAvailable(true);
        try {
            serialPort.setSerialPortParams(9600,
                SerialPort.DATABITS_8,
                SerialPort.STOPBITS_1,
                SerialPort.PARITY_NONE);
        } catch (UnsupportedCommOperationException e) {System.out.println(e);}
        readThread = new Thread(this);
        readThread.start();
    }

    public void run() {
        try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {System.out.println(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:
            break;
        case SerialPortEvent.DATA_AVAILABLE:
            byte[] readBuffer = new byte[20];

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


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

Comments(61)


1. View Comment

Hi Steven. It looks like your example program does something similar to what I need to do. I want to write a program which will wait for incoming calls from another computer. The other computer will be sending an order over the telephone line. I'm trying to understand whether such a listening program needs to "answer" the call or will this happen automatically in your program code above.

I would have suspected that the program should wait for the Ring Indicator event and then send a command to the modem in order to answer the call. After the call has been answered it would then start to respond to the Data Available event. Am I wrong about this? Thanks!


View Tutorial          By: Ben Hallinan at 2008-04-25 08:36:42
2. View Comment

How to run this Program?

View Tutorial          By: arwa at 2008-10-14 04:45:06
3. View Comment

Hi you will run this program just as you run any other java program. for example in a command prompt you will type java SimpleRead. Once you do that, the program will start listening on COM1 for any incoming data. So you would need another program such as <a href="http://www.java-samples.com/showtutorial.php?tutorialid=214">http://www.java-samples.com/showtutorial.php?tutorialid=214</a> to write to this COM port.

View Tutorial          By: Steven at 2008-10-14 09:03:28
4. View Comment

Once i run it gives the following error.Why "Port currently own by unknown windows application".I connected a GSM modem to serial port before run the program.are u think it is the reason for the error

View Tutorial          By: IDK at 2008-12-18 19:56:12
5. View Comment

Hi IDK,
You close any applications including browsers and then try to use the PORT. As the error suggests the port is in use. Try connecting to other COM port.


View Tutorial          By: Steven at 2008-12-30 03:14:33
6. View Comment

Hi,
I can run this program.But after running the command java SimpleRead. Just it run with out any error.

What i want is. "I am connecting my mobile in USB port,and port number is COM3. So i set the COM3 in above program. If any incoming calls come into the connected mobile, i need to inform this in screen, or just a msg with incoming phone number in cmd promt".

Can u help me to do this ?

Thanks and Regards,
JayarajMohan.J


View Tutorial          By: jayaraj at 2009-06-05 01:28:18
7. View Comment

Whne i run this code ,it does not return any ports.
the nextelement is null and therefore exits.
shouldnt ->
portList = CommPortIdentifier.getPortIdentifiers();
be some (object of CommPortIdentifier).getPortIdentifier ??


View Tutorial          By: amit at 2009-06-10 02:11:13
8. View Comment

Dude I want to send sms using GSM Mobile connected to COM1. can u advise me something?

View Tutorial          By: Funmarkaz at 2009-08-23 02:59:50
9. View Comment

Dear Friend,
Your programs is like the one i needed . But i had to write a program to read a port for example (port 5000) of another system . if the other system ip adress is 192.168.123.11 then how will be the code like .....Please help i am in trouble...


View Tutorial          By: thomas at 2009-11-02 00:38:18
10. View Comment

i use your program to read my GPS ( in COM11 ) . I could read it and get the string printed. But i need to Take that GPS string $GPRMC, 163126, V, 4335.2521, N, 08446.0900, W, 000.0, 173.2, 051206,006.1, W*62 . so i tryied using x.split(","); and get datas seperately printed..but i couldnt...Please help !!!! :))) help !!!

View Tutorial          By: Dinesh rajapaksha at 2009-11-17 07:25:19
11. View Comment

hi ... i want to receive SMS on the com port ... but this code doesn't show any output when SMS received... it is working for incoming calls but not for SMS ... can anyone help me plz....

View Tutorial          By: Ahsan at 2010-02-16 19:49:26
12. View Comment

i need a source to send and receive SMS through the usb port I
Mobile cable is connected to a computer and send Vdryaft computer is done via SMS


View Tutorial          By: morteza at 2010-03-03 01:53:09
13. View Comment

when i copy paste your program or source code
the first error occurred is the javax.comm.*;
it says that i don't have library for that..
how can I get or download it?


View Tutorial          By: hello at 2010-07-09 18:56:23
14. View Comment

Hi Steve.
I have two applications; 1 listening on com1 & its proprietary and my java appi which has to send data to the proprietary appi on com 1. the proprietary appi has to be running always and it owns com1. how can my appi be able to communicate with this proprietary appi on the same port


View Tutorial          By: Victor at 2010-08-18 01:22:49
15. View Comment

Hi Steve,

thanks for your code. It works, but I get this output òöõò÷ôôõ÷ôõô÷ôôô÷ðöõõöô...... maybe I am doing something wrong or I fortgot to configurate something.

Thanks for your help again. I appreciate any kind of help.


Thanks.


View Tutorial          By: Johnny at 2010-10-29 09:25:41
16. View Comment

Hi Johnny,

did you check whether the settings for the COM port are correct? i.e. if

serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);

matches the settings of your barcode scanner / modem / <insert arbitrary device here> ?

Kind regards
Frank


View Tutorial          By: Frank at 2010-11-13 13:16:57
17. View Comment

Hi i copied the same code n change the comport no .its has been compiled successfully but not getting any output..
Pls help me out...
Thanks in advance...


View Tutorial          By: Nidhi Puri at 2010-12-04 00:55:29
18. View Comment

i am not getting output by using this code..after changing port no.
i want to read sms data on pc port ...plz anyone can help me..


View Tutorial          By: dhaval at 2011-01-03 03:42:28
19. View Comment

i run this program. its not showing any runtime or compile time error. but when i receive a sms to mobile which i connect to COM port i cant read the message received in output screen.its full of square type of charectres.pls help me

View Tutorial          By: anand sp at 2011-03-07 10:11:37
20. View Comment

when i copy paste your program or source code
the first error occurred is the javax.comm.*;
it says that i don't have library for that..
how can I get or download it?


View Tutorial          By: Zordan at 2011-03-17 04:28:08
21. View Comment

Hello , How could i Run java.comm on eclipse
any one have any idea

Thanks


View Tutorial          By: Fiars at 2011-04-11 04:53:45
22. View Comment

thanks alot steven for the code. i'm try to automate my home using java code to communicate with microcontroller pic16f84a (which i've already programmed) using com1. if possible can u give me a hand by sending me your email address so that we can discuss about the system (it's a personal project of mine). thanks :)

View Tutorial          By: Roger at 2011-05-17 17:33:07
23. View Comment

can you tell me how can i install javax.comm.* library?
Where should I save it?


View Tutorial          By: chinthaka at 2011-06-22 09:30:29
24. View Comment

I am trying to connect mobile to PC. I put your example to Netbeans and have run it on Windows 7 (64 bits). My mobile is sending a text on COM1, but the portList on the PC ist empty (portList.hasMoreElements == false). I am affraid, that I would need to install (and register) the win32com.dll and/or javax.comm.properties, so that Netbeans can use them. Can somebody suggest if I am right?
If yes, how and where to install the above mentioned files?
if no, what can I do to make ports visible to Netbeans?


View Tutorial          By: Dedo at 2011-11-30 17:45:32
25. View Comment

About the javax.comm.* error, you need to include the comm.jar library. You can download from here
http://code.google.com/p/smslib/downloads/detail?name=javacomm20-win32.zip&can=2&q


View Tutorial          By: Nicolas Tourne at 2011-12-18 15:11:05
26. View Comment

how to run this program? give sample code to create serial port communication from win7 to mobile device using java

View Tutorial          By: meena at 2012-01-12 11:52:03
27. View Comment

Thnak you very much i got much of help for my project from your information.

View Tutorial          By: Xshay at 2012-01-21 06:26:49
28. View Comment

i need to send some file usin a bluetooth devicem control from java, how i can use that device from java

View Tutorial          By: igle85 at 2012-01-25 06:27:50
29. View Comment

I am wanting to use a Honeywell 4600g handheld scanner/imager. I need it to scan a barcode, and then input the data into a .pdf document. I am not familiar with code, java, etc. Can someone design something for me to open a COM port, read the data that is scanned, and then input to a blank document?
Please reply with info. Thank you.


View Tutorial          By: bugdrvr1970 at 2012-01-25 17:27:43
30. View Comment

Hi there, I was able to build this properly but here is the error I get when I try to run: Error loading win32com: java.lang.UnsatisfiedLinkError: no win32com in java.libr
ary.path

Any ideas?


View Tutorial          By: Damien at 2012-01-30 17:37:20
31. View Comment

i have a shimmer accelerometer(bluetooth). i need to use java to send data to the shimmer to trigger it to send data. when it send data, so that i can send it to the database. im using RXTX. can u help me??

View Tutorial          By: jason at 2012-03-22 04:05:08
32. View Comment

I have mobile connecting to pc 3 options come com port connection & java connection I connect with com port connection. Can it be connected with java connection how is it possible

View Tutorial          By: Sumit Sharma at 2012-04-13 16:32:15
33. View Comment

Detect OS of iphone using Java Code

View Tutorial          By: Naina at 2012-07-31 11:07:09
34. View Comment

Dudes

I used the above code for connecting rfid reader to java but i got this error when i run

gnu.io.PortInUseException: Unknown Application

anyone know how to solve this problem.


View Tutorial          By: Nithin p at 2013-01-06 06:54:33
35. View Comment

I get theses errors and apparrently it cannot find SerialPortEventListener and the import javax.comm.*. Please help. Do I need to add a jar file or something


Exception in thread "main" java.lang.NoClassDefFoundError: SerialPortEvent
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
at java.lang.Class.getMethod0(Unknown Source)
at java.lang.Class.getMethod(Unknown Source)
at sun.launcher.LauncherHelper.getMainMethod(Unknown Source)
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: SerialPortEvent
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 6 more


View Tutorial          By: Abhaya at 2013-02-20 22:42:18
36. View Comment

Hi,
I want to read the barcode and print it in a console in a simple java program as soon as the barcode scans on top of any barcode. Is there any way?

Thanks


View Tutorial          By: Santu at 2013-03-12 18:15:18
37. View Comment

Hey there, I was needing something exactly like this to read data from the serial port, a friend gave me this code a while ago and I´ve been working on it, and everything looks perfect, I created GUI for this so I´m getting the data on window so it looks a little nicer, but when I click on the .jar file from the project it doesn´t do anything... do you have any idea why is this happening??

Note: I´m working on NetBeans


View Tutorial          By: Jeffry at 2013-03-26 03:33:27
38. View Comment

i run above code in my netbean ide, i din't get output and any error or exception. how to communicate my modem for sending and receiving sms.

View Tutorial          By: manish sharma at 2013-04-03 05:28:40
39. View Comment

Reading the above comments and questions I have my own dilemma.
Do i need a computer to run this program? I really want my toaster to burn the bread in serial. Could you modify it for me to run it on a toaster?
If you can't, can you just come over and make my breakfast?


View Tutorial          By: running on toaster at 2013-04-23 02:20:43
40. View Comment

any one can send serial port communication using netbeans...
if it is video how to do a project it much better to lean myself...
Thank u


View Tutorial          By: prakash at 2013-07-01 15:44:48
41. View Comment

this code works for incoming call but not for incoming sms. please help me fix this.
thanks alot


View Tutorial          By: iman at 2013-08-20 16:21:48
42. View Comment

HOW DO I FIND MY COMM PORT NAME SO THAT I CAN SPECIFY IN ABV CODE

View Tutorial          By: RUTUJA at 2013-10-01 18:27:59
43. View Comment

BEST COMMENT EVER:
"Reading the above comments and questions I have my own dilemma.
Do i need a computer to run this program? I really want my toaster to burn the bread in serial. Could you modify it for me to run it on a toaster?
If you can't, can you just come over and make my breakfast?
"
COME ON GUYS, start from here, take the ideea and grow according to your needs!


View Tutorial          By: Mr.X at 2013-10-02 16:31:42
44. View Comment

the code works fine,i also tried the write code.that also works fine.But I want to use both of these simultaneously,is it possible?

View Tutorial          By: Joy at 2013-11-25 05:24:23
45. View Comment

I am running it within NetBeans. I set a breakpoint at:
portlist=CommPortIdentifier.getPortIdentifiers():
I do F& and is shows:
public static SecurityManager getSecurityManager(){
return security
but security is null so portlist becomse null and the program ends.
Any idea how to get past this?
Thanks,


View Tutorial          By: PeteC at 2014-02-22 18:57:14
46. View Comment

I copied the same program for execution...
my program is to read data from rfid reader with is connected to the computer through usb...
but there is error in importing javax.comm.*
so the whole program has errors.
what is the problem ans please suggest solutions


View Tutorial          By: Anusha at 2014-05-14 14:24:19
47. View Comment

i am trying to create a handy and powerful barcode reader, any suggestion on this?

View Tutorial          By: incoming barcode scanner at 2014-06-23 04:23:42
48. View Comment

i have created a UI in swing now i want to read the data from the arduino microcontroller. Can you suggest me some ideas?

View Tutorial          By: Ashish Gaurkhede at 2014-09-08 08:21:04
49. View Comment

hi....!
This program is working well in command prompt
when i run this program in eclipse the statment
portList.hasMoreElements() returns false but it returns true when run in command prompt.......


View Tutorial          By: param at 2014-10-15 07:02:49
50. View Comment

i am using the same code to read data from an RFID reader. I am using serial to usb cable. code looks fine but when it runs it shows "port occupied by unknown windows application"" , it remains same after changing port no. :(
can anyone help me in figuring out what is wrong ??
thanks in advance :)


View Tutorial          By: JayS at 2015-02-03 21:31:36
51. View Comment

Hi,

I have a error like the import javax.comm.* not exist. what i need to do?


View Tutorial          By: manigandavenkatesh at 2015-02-12 05:52:05
52. View Comment

dis prgrm is not giving me any ouput..i need to read an IWR..pls help me in dis..

View Tutorial          By: singh at 2015-02-19 12:16:31
53. View Comment

where i put this rar file to include comm api

View Tutorial          By: shubham bansal at 2015-02-20 12:13:16
54. View Comment

Whenever i run this program, it terminates immediately without throwing any error. Kindly help what to do ?

View Tutorial          By: Salman at 2015-03-26 08:23:32
55. View Comment

frnds i want serial communication over beaglebone where one device will be attached with serial port o beaglebone and other will be attached with usb port. and now i want to read data from device 1(serial port) and send it to device 2(usb port). PLZ HELP ME with the situation....

View Tutorial          By: Rajneesh at 2015-04-12 11:23:16
56. View Comment

Hi,
I'm having a problem with the above code that is when i try to compile the above code in eclipse there is a compile time error near
SimpleRead reader = new SimpleRead();
ie. SimpleRead connot be resolved to be as a type
i'm not able to resolve the problem
PLS HELP.......


View Tutorial          By: sushanth at 2015-05-04 07:32:17
57. View Comment

Just Clean Project(deleting all compiled code) and Rebuild It Works in JSP

View Tutorial          By: Shivakumar at 2015-05-04 08:20:38
58. View Comment

hi thanks for your tutorial, but I can`t run your code on Raspberry pi because of following error: can`t find javax.comm.properties!. can you help me?
thanks


View Tutorial          By: yashar at 2015-05-29 18:57:30
59. View Comment

I am trying to execute the same code but still unable to get output.Output window is not getting display. COM Port is COM10, doing this change in code but still no output.I have connected LM35 to arduino and its working. Data is being received and displayed at hyper terminal.Why so?pls help .urgent.thank you.
Can anyone pls show what is expected output window?


View Tutorial          By: Sona at 2015-06-11 18:35:13
60. View Comment

Whenever i run this program, it terminates immediately without throwing any error. Kindly help what to do ?

View Tutorial          By: Gopi at 2015-08-19 06:55:41
61. View Comment

Ho,i have created read and write program on different computer ,but i didn't get any display ..please can u help me..if u don't mind...?

View Tutorial          By: niranjan at 2015-08-26 09:02:57

Your name (required):


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


Your sites URL (optional):


Your comments:



More Tutorials by Steven Lim
Write to a COM port using Java program
Read from a COM port using Java program

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 use 'implements Runnable' in Java
Integer: byte, short, int, and long data types in Java
Student marks calculation program in Java
compareTo( ) in Java
Stack example in Java - push(), pop(), empty(), search()
Count number of vowels, consonants and digits in a String in Java
How to Send SMS using Java Program (full code sample included)
Read from a COM port using Java program
Calculate gross salary in Java
XML and Java - Parsing XML using Java Tutorial
Multiple Inheritance sample in Java
TCP Server and TCP Client in Java
append() in Java
Multidimensional or arrays of arrays in Java
The Basic Structure of a Simple Java program
Most Emailed Articles (in Java)
What is Java?
inheritance in Java
How to Send SMS using Java Program (full code sample included)
Using PrintWriter in Java
Booleans in java
Read from a COM port using Java program
Handling Fractions in Java
package com.sun.speech.freetts does not exist.
Summary of Operators in Java
Use of return statement in Java
The java Buzzwords
Update contents of a file within a jar file
emulator 0 terminated while waiting for it to register!
FileReader and FileWriter example program in Java
Introducing Nested and Inner Classes