Programming Tutorials

Sample Java program shows how to write to COM port using Java.

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

This Sample Java program shows how to write to 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 http://java.sun.com/products/javacomm/. 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.io.*;
import java.util.*;
import javax.comm.*;

public class SimpleWrite {
    static Enumeration portList;
    static CommPortIdentifier portId;
    static String messageString = "Hello, world!\n";
    static SerialPort serialPort;
    static OutputStream outputStream;

    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")) {
                    try {
                        serialPort = (SerialPort)
                            portId.open("SimpleWriteApp", 2000);
                    } catch (PortInUseException e) {}
                    try {
                        outputStream = serialPort.getOutputStream();
                    } catch (IOException e) {}
                    try {
                        serialPort.setSerialPortParams(9600,
                            SerialPort.DATABITS_8,
                            SerialPort.STOPBITS_1,
                            SerialPort.PARITY_NONE);
                    } catch (UnsupportedCommOperationException e) {}
                    try {
                        outputStream.write(messageString.getBytes());
                    } catch (IOException e) {}
                }
            }
        }
    }
}





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)