Read from a COM port using Java program

By: Steven Lim Viewed: 153135 times    

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

Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial

Subscribe to Tutorials

Related Tutorials

Archived Comments

1. Hi Steven. It looks like your example program does
View Tutorial          By: Ben Hallinan at 2008-04-25 08:36:42

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

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

4. Hi you will run this program just as you run any o
View Tutorial          By: Steven at 2008-10-14 09:03:28

5. Once i run it gives the following error.Why "
View Tutorial          By: IDK at 2008-12-18 19:56:12

6. Hi IDK,
You close any applications includin

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

7. Hi,
I can run this program.But after

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

8. Whne i run this code ,it does not return any ports
View Tutorial          By: amit at 2009-06-10 02:11:13

9. Whne i run this code ,it does not return any ports
View Tutorial          By: amit at 2009-06-10 02:15:32

10. Dude I want to send sms using GSM Mobile connected
View Tutorial          By: Funmarkaz at 2009-08-23 02:59:50

11. Dear Friend,
Your programs is like the one

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

12. i use your program to read my GPS ( in COM11 ) .
View Tutorial          By: Dinesh rajapaksha at 2009-11-17 07:25:19

13. hi ... i want to receive SMS on the com port ... b
View Tutorial          By: Ahsan at 2010-02-16 19:49:26

14. hi ... i want ot receive SMS on PC /... but is d
View Tutorial          By: Ahsan at 2010-02-16 21:42:51

15. i need a source to send and receive SMS through th
View Tutorial          By: morteza at 2010-03-03 01:53:09

16. I tried with this.. I am able to get a ring alert
View Tutorial          By: satish at 2010-06-20 11:01:47

17. I tried with this.. I am able to get a ring alert
View Tutorial          By: satish at 2010-06-20 11:03:33

18. when i copy paste your program or source code

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

19. Hi Steve.
I have two applications; 1 listen

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

20. Hi Steve,

thanks for your code. It

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

21. Hi Johnny,

did you check whether th

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

22. Hi i copied the same code n change the comport no
View Tutorial          By: Nidhi Puri at 2010-12-04 00:55:29

23. i am not getting output by using this code..after
View Tutorial          By: dhaval at 2011-01-03 03:42:28

24. i run this program. its not showing any runtime or
View Tutorial          By: anand sp at 2011-03-07 10:11:37

25. when i copy paste your program or source code

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

26. Hello , How could i Run java.comm on eclipse

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

27. thanks alot steven for the code. i'm try to automa
View Tutorial          By: Roger at 2011-05-17 17:33:07

28. can you tell me how can i install javax.comm.* lib
View Tutorial          By: chinthaka at 2011-06-22 09:30:29

29. hi there i was wondering how to send data from jav
View Tutorial          By: bon at 2011-09-22 03:09:57

30. how can i get both the simpleread and simplewrite
View Tutorial          By: ALBERT at 2011-10-04 19:48:48

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

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

33. I am trying to connect mobile to PC. I put your ex
View Tutorial          By: Dedo at 2011-11-30 17:45:32

34. About the javax.comm.* error, you need to include
View Tutorial          By: Nicolas Tourne at 2011-12-18 15:11:05

35. how to run this program? give sample code to cre
View Tutorial          By: meena at 2012-01-12 11:52:03

36. Thnak you very much i got much of help for my proj
View Tutorial          By: Xshay at 2012-01-21 06:26:49

37. Hi, Steven! Is it possible to send data through X2
View Tutorial          By: Agajan at 2012-01-25 06:17:36

38. i need to send some file usin a bluetooth devicem
View Tutorial          By: igle85 at 2012-01-25 06:27:50

39. I am wanting to use a Honeywell 4600g handheld sca
View Tutorial          By: bugdrvr1970 at 2012-01-25 17:24:38

40. I am wanting to use a Honeywell 4600g handheld sca
View Tutorial          By: bugdrvr1970 at 2012-01-25 17:27:43

41. Hi there, I was able to build this properly but he
View Tutorial          By: Damien at 2012-01-30 17:37:20

42. i have a shimmer accelerometer(bluetooth). i need
View Tutorial          By: jason at 2012-03-22 04:05:08

43. I have mobile connecting to pc 3 options come com
View Tutorial          By: Sumit Sharma at 2012-04-13 16:32:15

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

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

46. Dudes

I used the abov

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

47. I get theses errors and apparrently it cannot find
View Tutorial          By: Abhaya at 2013-02-20 22:42:18

48. Hi,
I want to read the barcode and print it

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

49. Hey there, I was needing something exactly like th
View Tutorial          By: Jeffry at 2013-03-26 03:33:27

50. i run above code in my netbean ide, i din't get ou
View Tutorial          By: manish sharma at 2013-04-03 05:28:40

51. Reading the above comments and questions I have my
View Tutorial          By: running on toaster at 2013-04-23 02:20:43

52. any one can send serial port communication using n
View Tutorial          By: prakash at 2013-07-01 15:44:48

53. this code works for incoming call but not for inco
View Tutorial          By: iman at 2013-08-20 16:21:48

54. HOW DO I FIND MY COMM PORT NAME SO THAT I CAN SPEC
View Tutorial          By: RUTUJA at 2013-10-01 18:27:59

55. BEST COMMENT EVER:
"Reading the above

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

56. the code works fine,i also tried the write code.th
View Tutorial          By: Joy at 2013-11-25 05:24:23

57. I am running it within NetBeans. I set a breakpoin
View Tutorial          By: PeteC at 2014-02-22 18:57:14

58. I copied the same program for execution...

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

59. i am trying to create a handy and powerful barcode
View Tutorial          By: incoming barcode scanner at 2014-06-23 04:23:42

60. i have created a UI in swing now i want to read th
View Tutorial          By: Ashish Gaurkhede at 2014-09-08 08:21:04

61. hi....!
This program is working well in co

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

62. i am using the same code to read data from an RFID
View Tutorial          By: JayS at 2015-02-03 21:31:36

63. Hi,

I have a error like the import

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

64. dis prgrm is not giving me any ouput..i need to re
View Tutorial          By: singh at 2015-02-19 12:16:31

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

66. Whenever i run this program, it terminates immedia
View Tutorial          By: Salman at 2015-03-26 08:23:32

67. scm is an alternative to javax.comm for serial po
View Tutorial          By: VICTOR at 2015-03-28 07:36:32

68. frnds i want serial communication over beaglebone
View Tutorial          By: Rajneesh at 2015-04-12 11:23:16

69. Hi,
I'm having a problem with the above cod

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

70. Just Clean Project(deleting all compiled code) and
View Tutorial          By: Shivakumar at 2015-05-04 08:20:38

71. hi thanks for your tutorial, but I can`t run your
View Tutorial          By: yashar at 2015-05-29 18:57:30

72. I am trying to execute the same code but still una
View Tutorial          By: Sona at 2015-06-11 18:35:13

73. Whenever i run this program, it terminates immedia
View Tutorial          By: Gopi at 2015-08-19 06:55:41

74. Ho,i have created read and write program on differ
View Tutorial          By: niranjan at 2015-08-26 09:02:57

75. I am trying to work on serial communication in MAC
View Tutorial          By: sruthi at 2016-05-28 07:23:55

76. This was very helpful, thank you so much. It's the
View Tutorial          By: Chris at 2016-06-21 13:49:16

77. Hello,
I am trying to read from Adruino ser

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

78. Hi. your code is successfully compiling in my lapt
View Tutorial          By: Abhay at 2016-11-10 06:30:22

79. how to read
from byte array ...
its

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

80. how to read new line in this code plz help me

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

81. I want to read incoming sms from the phone connect
View Tutorial          By: Parshant gupta at 2016-12-30 17:51:51

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

cannot update times viewed