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

By: Johanes Emailed: 1700 times Printed: 2202 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 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) {}
                }
            }
        }
    }
}

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(9)


1. View Comment

Hello,

I've got javax.comm and followed carefully the installation guide on Linux(ubuntu9.04), when I try to run java BlackBox I get error below:

Exception in thread "main" java.lang.NoClassDefFoundError: javax/comm/NoSuchPortException
Caused by: java.lang.ClassNotFoundException: javax.comm.NoSuchPortException
at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:319)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:264)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:332)
Could not find the main class: BlackBox. Program will exit.

Please help. what should I do?


View Tutorial          By: Ashkan at 2009-12-19 21:51:19
2. View Comment

hai
i can run this program bt 1 exceptions returned plz help me


Error loading SolarisSerial: java.lang.UnsatisfiedLinkError: no SolarisSerialParallel in java.library.path
Caught java.lang.UnsatisfiedLinkError: com.sun.comm.SolarisDriver.readRegistrySerial(Ljava/util/Vector;Ljava/lang/String;)I while loading driver com.sun.comm.SolarisDriver
Error loading SolarisSerial: java.lang.UnsatisfiedLinkError: no SolarisSerialParallel in java.library.path
Caught java.lang.UnsatisfiedLinkError: com.sun.comm.SolarisDriver.readRegistrySerial(Ljava/util/Vector;Ljava/lang/String;)I while loading driver com.sun.comm.SolarisDriver


View Tutorial          By: Raheela at 2010-05-25 21:59:38
3. View Comment

Hello,
i was run your given program in eclipse and command prompt but it doesn't give any output...
it always terminate in eclipse, how can i run this code??
please help me......


View Tutorial          By: vishnu chauhan at 2013-01-24 11:42:16
4. View Comment

Hello,

When I put the source code in Ecplise I get the win32.dll error. Cannot run IA win32.dll on a AMD 64bit platform. Can anyone tell me how to fix this instead of using a 32 bit platform.

thanks


View Tutorial          By: Pascal at 2013-03-25 09:12:47
5. View Comment

import gnu.io.*;
import java.io.*;


public class ListPortClass implements SerialPortEventListener
{

public static void main(String[] s)
{
try
{
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(\"/dev/ttyS0\");
if (portIdentifier.isCurrentlyOwned())
System.out.println(\"Port in use!\");

else {
System.out.println(portIdentifier.getName());

SerialPort serialPort = (SerialPort) portIdentifier.open(\"ListPortClass\",300);
int b = serialPort.getBaudRate();
System.out.println(Integer.toString(b));
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
serialPort.notifyOnCarrierDetect(true);

serialPort.setOutputBufferSize(100);
serialPort.setInputBufferSize(1000);
serialPort.addEventListener(new ListPortClass());
OutputStream mOutputToPort = serialPort.getOutputStream();

InputStream mInputFromPort = serialPort.getInputStream();
PrintWriter pr=new PrintWriter(mOutputToPort);
FileReader fr=new FileReader(\"/root/Desktop/satya/input.txt\");
BufferedReader br =new BufferedReader(fr);
String st=br.readLine();
System.out.print(st);
mOutputToPort.flush();
mOutputToPort.flush();
System.out.println(\"beginning to Write . \\r\\n\");
mOutputToPort.write((\"$B\").getBytes());

System.out.println(\" Written to Port. \\r\\n\");
mOutputToPort.flush();
System.out.println(\"Waiting for Reply \\r\\n\");

//Thread.sleep(50);
System.out.println(mInputFromPort.available());
byte mBytesIn [] = new byte[20];
int n=mInputFromPort.read(mBytesIn);
//mInputFromPort.read(mBytesIn);
String value = new String(mBytesIn);
System.out.println(\"Response from Serial Device: \"+value);
mOutputToPort.close();
mInputFromPort.close();
}
}
catch (Exception ex)
{
System.out.println(\"Exception : \" + ex.getMessage());
}

}


@Override
public void serialEvent(SerialPortEvent spe) {
System.out.println(\"data available\");
}
}


This is my java code for Communicate with ETIM machine....
whenever the machine gets the data of input.txt file, it gives the output as its version .

But while excecuting this code, machine not giving any response back...please solve my problem...

my OS:LINUX


View Tutorial          By: Anonymous at 2013-03-29 02:39:00
6. View Comment

Hi
I can compile it
root$ javac -cp .:comm-2.0.jar SimpleCOMPortWriter.java but it fails on execution.

Please advise.



Exception in thread "main" java.lang.NoClassDefFoundError: javax/comm/PortInUseException
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2531)
at java.lang.Class.getMethod0(Class.java:2774)
at java.lang.Class.getMethod(Class.java:1663)
at sun.launcher.LauncherHelper.getMainMethod(LauncherHelper.java:494)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:486)
Caused by: java.lang.ClassNotFoundException: javax.comm.PortInUseException
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 6 more


View Tutorial          By: Tebogo Modiselle at 2014-10-31 08:47:09
7. View Comment

how to write an byte array containing 10 different elements to serial port and read it back in the same order of elements and print.

View Tutorial          By: sanjana at 2015-01-17 06:32:41
8. View Comment

no output is shown

View Tutorial          By: shubham bansal at 2015-02-21 15:36:31
9. View Comment

no output as well, i'm getting portlist and portId as NULL, so no loop

View Tutorial          By: raul at 2015-10-09 20:05:02

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)
Read from a COM port using Java program
The Basic Structure of a Simple Java program
XML and Java - Parsing XML using Java Tutorial
FileReader and FileWriter example program in Java
How to use ArrayList in Java
Student marks calculation program in Java
Garbage collection and Finalize() method
Count number of vowels, consonants and digits in a String in Java
Abstract classes in Java
Integer: byte, short, int, and long data types in Java
Calendar - sample program in Java
Recursion in java
Reading from a file and writing to a file using Java program
Inheritance Example in Java
Most Emailed Articles (in Java)
Read from a COM port using Java program
How to use ArrayList in Java
Write to a COM port using Java program
How to access instance from an inner class and accessing outer class variables in java
Data Types in Java
Method Overloading (function overloading) in Java
Tomcat and httpd configured in port 8080 and 80
Save/Write/Read image file from/to a database using Java program
Java program for changeable wrapper class
History of Java
Using jar utility in Java - A jar tutorial
FilenameFilter - sample program in Java
Observable class and the sample program in Java
Integer: byte, short, int, and long data types in Java
Sample Java program shows how to write to COM port using Java.