Read from a COM port using Java program

By: Steven Lim  

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




Archived Comments

1. CurtisQuef
View Tutorial          By: CurtisQuef at 2017-06-13 06:01:15

2. RichardCemo
View Tutorial          By: RichardCemo at 2017-06-13 00:49:31

3. Michaelruink
View Tutorial          By: Michaelruink at 2017-06-08 00:20:46

4. CurtisQuef
View Tutorial          By: CurtisQuef at 2017-05-25 10:21:15

5. RichardCemo
View Tutorial          By: RichardCemo at 2017-05-25 01:14:45

6. RichardCemo
View Tutorial          By: RichardCemo at 2017-05-19 05:26:31

7. CurtisQuef
View Tutorial          By: CurtisQuef at 2017-05-17 16:55:33

8. Thomasmi
View Tutorial          By: Thomasmi at 2017-05-15 02:46:49

9. RichardCemo
View Tutorial          By: RichardCemo at 2017-05-12 13:54:57

10. XRumerTest
View Tutorial          By: XRumerTest at 2017-05-08 17:53:04

11. XRumerTest
View Tutorial          By: XRumerTest at 2017-05-08 03:29:48

12. CurtisQuef
View Tutorial          By: CurtisQuef at 2017-05-04 23:47:50

13. jaynevg69
View Tutorial          By: fernandoue18 at 2017-05-02 20:58:46

14. RichardCemo
View Tutorial          By: RichardCemo at 2017-05-01 23:08:19

15. EugenePn
View Tutorial          By: EugenePn at 2017-04-11 09:28:38

16. CurtisQuef
View Tutorial          By: CurtisQuef at 2017-04-06 20:18:54

17. tashabp11
View Tutorial          By: carleneep2 at 2017-04-06 20:05:30

18. Randyzek
View Tutorial          By: Randyzek at 2017-04-04 02:15:08

19. Randyzek
View Tutorial          By: Randyzek at 2017-04-04 02:15:01

20. ghkkll
View Tutorial          By: ghkkll at 2017-03-30 22:20:20

21. RichardCemo
View Tutorial          By: RichardCemo at 2017-03-25 16:20:37

22. BrandonNawn
View Tutorial          By: BrandonNawn at 2017-03-23 14:34:58

23. CurtisQuef
View Tutorial          By: CurtisQuef at 2017-03-22 00:12:11

24. XRumerTest
View Tutorial          By: XRumerTest at 2017-03-21 03:58:39

25. CurtisQuef
View Tutorial          By: CurtisQuef at 2017-03-20 10:04:41

26. CurtisQuef
View Tutorial          By: CurtisQuef at 2017-03-19 08:17:40

27. CurtisQuef
View Tutorial          By: CurtisQuef at 2017-03-19 06:21:21

28. CurtisQuef
View Tutorial          By: CurtisQuef at 2017-03-18 07:15:08

29. CurtisQuef
View Tutorial          By: CurtisQuef at 2017-03-17 10:51:10

30. CurtisQuef
View Tutorial          By: CurtisQuef at 2017-03-15 20:12:57

31. CurtisQuef
View Tutorial          By: CurtisQuef at 2017-03-15 18:36:22

32. CurtisQuef
View Tutorial          By: CurtisQuef at 2017-03-14 22:53:07

33. CurtisQuef
View Tutorial          By: CurtisQuef at 2017-03-14 01:34:56

34. RichardCemo
View Tutorial          By: RichardCemo at 2017-03-09 03:46:11

35. RichardCemo
View Tutorial          By: RichardCemo at 2017-03-02 00:10:21

36. ghjukliokss
View Tutorial          By: ghjukliokss at 2017-02-24 19:09:12

37. CurtisQuef
View Tutorial          By: CurtisQuef at 2017-02-22 04:39:53

38. CurtisQuef
View Tutorial          By: CurtisQuef at 2017-01-25 16:07:55

39. I want to read incoming sms from the phone connected to pc using usb. Can you please help me to achi
View Tutorial          By: Parshant gupta at 2016-12-30 17:51:51

40. how to read new line in this code plz help me
its urgent.

View Tutorial          By: amit gavli at 2016-12-23 07:22:12

41. how to read
from byte array ...
its urgent plz help me...

View Tutorial          By: amit gavli at 2016-12-22 13:51:30

42. Hi. your code is successfully compiling in my laptop. But, it is unable to run. I checked and confir
View Tutorial          By: Abhay at 2016-11-10 06:30:22

43. Hello,
I am trying to read from Adruino serial port. Your code works, but I receive extra unr

View Tutorial          By: Masoud at 2016-09-06 16:41:13

44. This was very helpful, thank you so much. It's the best example for a beginner like me that I've fou
View Tutorial          By: Chris at 2016-06-21 13:49:16

45. I am trying to work on serial communication in MAC OS. I already did this same coding part using jav
View Tutorial          By: sruthi at 2016-05-28 07:23:55

46. Ho,i have created read and write program on different computer ,but i didn't get any display ..pleas
View Tutorial          By: niranjan at 2015-08-26 09:02:57

47. Whenever i run this program, it terminates immediately without throwing any error. Kindly help what
View Tutorial          By: Gopi at 2015-08-19 06:55:41

48. I am trying to execute the same code but still unable to get output.Output window is not getting dis
View Tutorial          By: Sona at 2015-06-11 18:35:13

49. hi thanks for your tutorial, but I can`t run your code on Raspberry pi because of following error: c
View Tutorial          By: yashar at 2015-05-29 18:57:30

50. Just Clean Project(deleting all compiled code) and Rebuild It Works in JSP
View Tutorial          By: Shivakumar at 2015-05-04 08:20:38

51. Hi,
I'm having a problem with the above code that is when i try to compile the above code in

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

52. frnds i want serial communication over beaglebone where one device will be attached with serial port
View Tutorial          By: Rajneesh at 2015-04-12 11:23:16

53. scm is an alternative to javax.comm for serial port communication.
Wiki : http://www.e

View Tutorial          By: VICTOR at 2015-03-28 07:36:32

54. Whenever i run this program, it terminates immediately without throwing any error. Kindly help what
View Tutorial          By: Salman at 2015-03-26 08:23:32

55. where i put this rar file to include comm api
View Tutorial          By: shubham bansal at 2015-02-20 12:13:16

56. 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

57. 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

58. i am using the same code to read data from an RFID reader. I am using serial to usb cable. code look
View Tutorial          By: JayS at 2015-02-03 21:31:36

59. hi....!
This program is working well in command prompt
when i run this program in ecl

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

60. i have created a UI in swing now i want to read the data from the arduino microcontroller. Can you s
View Tutorial          By: Ashish Gaurkhede at 2014-09-08 08:21:04

61. 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

62. I copied the same program for execution...
my program is to read data from rfid reader with i

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

63. I am running it within NetBeans. I set a breakpoint at:
portlist=CommPortIdentifier.getPortId

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

64. the code works fine,i also tried the write code.that also works fine.But I want to use both of these
View Tutorial          By: Joy at 2013-11-25 05:24:23

65. BEST COMMENT EVER:
"Reading the above comments and questions I have my own dilemma.

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

66. 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

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

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

68. any one can send serial port communication using netbeans...
if it is video how to do a proje

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

69. Reading the above comments and questions I have my own dilemma.
Do i need a computer to run t

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

70. i run above code in my netbean ide, i din't get output and any error or exception. how to communicat
View Tutorial          By: manish sharma at 2013-04-03 05:28:40

71. Hey there, I was needing something exactly like this to read data from the serial port, a friend gav
View Tutorial          By: Jeffry at 2013-03-26 03:33:27

72. Hi,
I want to read the barcode and print it in a console in a simple java program as soon as

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

73. I get theses errors and apparrently it cannot find SerialPortEventListener and the import javax.com
View Tutorial          By: Abhaya at 2013-02-20 22:42:18

74. Dudes

I used the above code for connecting rfid reader to java but i go

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

75. Detect OS of iphone using Java Code
View Tutorial          By: Naina at 2012-07-31 11:07:09

76. what is the output of this sample code?
View Tutorial          By: shumana at 2012-07-20 20:42:59

77. I have mobile connecting to pc 3 options come com port connection & java connection I connect w
View Tutorial          By: Sumit Sharma at 2012-04-13 16:32:15

78. i have a shimmer accelerometer(bluetooth). i need to use java to send data to the shimmer to trigger
View Tutorial          By: jason at 2012-03-22 04:05:08

79. Hi there, I was able to build this properly but here is the error I get when I try to run: Error loa
View Tutorial          By: Damien at 2012-01-30 17:37:20

80. I am wanting to use a Honeywell 4600g handheld scanner/imager. I need it to scan a barcode, and the
View Tutorial          By: bugdrvr1970 at 2012-01-25 17:27:43

81. I am wanting to use a Honeywell 4600g handheld scanner/imager. I need it to scan a barcode, and the
View Tutorial          By: bugdrvr1970 at 2012-01-25 17:24:38

82. i need to send some file usin a bluetooth devicem control from java, how i can use that device from
View Tutorial          By: igle85 at 2012-01-25 06:27:50

83. Hi, Steven! Is it possible to send data through X25 port using above example. If it is possible can
View Tutorial          By: Agajan at 2012-01-25 06:17:36

84. 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

85. how to run this program? give sample code to create serial port communication from win7 to mobile
View Tutorial          By: meena at 2012-01-12 11:52:03

86. About the javax.comm.* error, you need to include the comm.jar library. You can download from here <
View Tutorial          By: Nicolas Tourne at 2011-12-18 15:11:05

87. I am trying to connect mobile to PC. I put your example to Netbeans and have run it on Windows 7 (64
View Tutorial          By: Dedo at 2011-11-30 17:45:32

88. Congratulations! Pretty good information!
View Tutorial          By: Vitor Oliveira at 2011-10-24 11:10:09

89. zyrtec
View Tutorial          By: zyrtec at 2011-10-16 13:30:26

90. how can i get both the simpleread and simplewrite to work together?
View Tutorial          By: ALBERT at 2011-10-04 19:48:48

91. hi there i was wondering how to send data from java to the com port.... not only read...
View Tutorial          By: bon at 2011-09-22 03:09:57

92. 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

93. thanks alot steven for the code. i'm try to automate my home using java code to communicate with mic
View Tutorial          By: Roger at 2011-05-17 17:33:07

94. 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

95. when i copy paste your program or source code
the first error occurred is the javax.comm.*;
View Tutorial          By: Zordan at 2011-03-17 04:28:08

96. i run this program. its not showing any runtime or compile time error. but when i receive a sms to m
View Tutorial          By: anand sp at 2011-03-07 10:11:37

97. i am not getting output by using this code..after changing port no.
i want to read sms data o

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

98. Hi i copied the same code n change the comport no .its has been compiled successfully but not gettin
View Tutorial          By: Nidhi Puri at 2010-12-04 00:55:29

99. Hi Johnny,

did you check whether the settings for the COM port are correct? i.e. if
View Tutorial          By: Frank at 2010-11-13 13:16:57

100. Hi Steve,

thanks for your code. It works, but I get this output ò&Atild

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

101. Hi Steve.
I have two applications; 1 listening on com1 & its proprietary and my java appi

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

102. when i copy paste your program or source code
the first error occurred is the javax.comm.*;
View Tutorial          By: hello at 2010-07-09 18:56:23

103. I tried with this.. I am able to get a ring alert when a call comes.. But When it comes for SMS, I a
View Tutorial          By: satish at 2010-06-20 11:03:33

104. I tried with this.. I am able to get a ring alert when a call comes.. But When it comes for SMS, I a
View Tutorial          By: satish at 2010-06-20 11:01:47

105. i need a source to send and receive SMS through the usb port I
Mobile cable is connected to

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

106. hi ... i want ot receive SMS on PC /... but is doesnt work ...but it is working for incomming call
View Tutorial          By: Ahsan at 2010-02-16 21:42:51

107. hi ... i want to receive SMS on the com port ... but this code doesn't show any output when SMS rec
View Tutorial          By: Ahsan at 2010-02-16 19:49:26

108. i use your program to read my GPS ( in COM11 ) . I could read it and get the string printed. But i
View Tutorial          By: Dinesh rajapaksha at 2009-11-17 07:25:19

109. Dear Friend,
Your programs is like the one i needed . But i had to write a program to read a

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

110. 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

111. Whne i run this code ,it does not return any ports.
the nextelement is null and therefore exi

View Tutorial          By: amit at 2009-06-10 02:15:32

112. Whne i run this code ,it does not return any ports.
the nextelement is null and therefore exi

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

113. Hi,
I can run this program.But after running the command java SimpleRead. Just it run w

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

114. Hi IDK,
You close any applications including browsers and then try to use the PORT. As the er

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

115. Once i run it gives the following error.Why "Port currently own by unknown windows application&
View Tutorial          By: IDK at 2008-12-18 19:56:12

116. Hi you will run this program just as you run any other java program. for example in a command prompt
View Tutorial          By: Steven at 2008-10-14 09:03:28

117. How to run this Program?
View Tutorial          By: arwa at 2008-10-14 04:45:48

118. How to run this Program?
View Tutorial          By: arwa at 2008-10-14 04:45:06

119. Hi Steven. It looks like your example program does something similar to what I need to do. I want to
View Tutorial          By: Ben Hallinan at 2008-04-25 08:36:42


Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial