Sunteți pe pagina 1din 7

7/1/2015

SampleJavaprogramshowshowtowritetoCOMportusingJava.

AdsbyGoogle

Home

Submit Tutorial

JavaExample

Latest Tutorials

JavaTutorials

JavaSourceCode

JavaDownload

Subscribe in a reader

Android | ASP.net | C | C++ | C# | Cocoa | Java | JavaScript | JSP | J2ME | JSF | JDBC| Struts | HTML5 | PHP | Perl | Python | Ruby | VB.net | Trends
Search

Sample Java program shows how to write to COM port using Java.
By: Johanes Emailed: 1174 times Printed: 443 times

Like

15k

Latest comments
87%

87%

By: david I have a mac book dual bo

Android
Java
Javascript
JSF
JSP
J2ME

By: RAJA What is the difference be

Java Beans

By: ivex Thanks, you save my day!

EJB

By: sandhya i want to how to run a pa

JDBC

By: Hardik Negandhi Can you help me input 15

Hibernate

By: suresh l Hi, thi's sursh laveti, a


By: ishika nice explanation indeed,

Struts
Office 365
SAP

By: Sayed maseer I need you to Write me a

WebServices

By: yannoo95170 Very nice tutorial :)

XML
Certification

ThisSampleJavaprogramshowshowtowritetoCOMportusingJava.
Ifyouareoneofthoselivingstillinthe20thcenturythenyourJDKprobablydoesn'tcomewiththe
JavaCOMMAPI.SoyouwouldhavetodownloadtheJavaCommApifrom
http://java.sun.com/products/javacomm/.Ontheotherhandifyouareusingoneofthelaterversionsof
JDKthentheJavaCommAPIshouldbeinbuilttogetherwithyourJDK.Onceyouhavethisthen
createasampleprogramtoreadfromthePC'sCOMport.Andthencopyandpastethebelowcode
intothatprogram.Compileandrunit.Ifthecompilationfailsthenitisprobablyduetosomeclasspath
problem.Youwillhavetoaddthejavax.commapitoyourclasspathproperly.

Interview

Sponsored Links

importjava.io.*;
importjava.util.*;
importjavax.comm.*;
publicclassSimpleWrite{
staticEnumerationportList;
staticCommPortIdentifierportId;
staticStringmessageString="Hello,world!\n";
staticSerialPortserialPort;
staticOutputStreamoutputStream;
publicstaticvoidmain(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(PortInUseExceptione){}
try{
outputStream=serialPort.getOutputStream();

http://www.javasamples.com/showtutorial.php?tutorialid=214

1/7

7/1/2015

SampleJavaprogramshowshowtowritetoCOMportusingJava.

}catch(IOExceptione){}
try{
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
}catch(UnsupportedCommOperationExceptione){}
try{
outputStream.write(messageString.getBytes());
}catch(IOExceptione){}
}
}
}
}
}

87%

87%

88%

87%

87%

87%

72%

67%

40%

87%

87%

87%

33%

87%

JavaHome|AllJavaTutorials|LatestJavaTutorials

SponsoredLinks
87%

50%

Ifthistutorialdoesn't
answeryourquestion,or
youhaveaspecific
question,justaskan
experthere.Postyour
questiontogetadirect
answer.

Get tutorials direct to


your email:

Comments(8)
Subscribe

1.

ViewComment
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:

FindusonFacebook

Java
Samples.com
Like
15,461peoplelikeJava

Samples.com.
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?

Facebooksocialplugin

ViewTutorialBy:Ashkanat2009121921:51:19
http://www.javasamples.com/showtutorial.php?tutorialid=214

2/7

7/1/2015

2.

SampleJavaprogramshowshowtowritetoCOMportusingJava.

ViewComment
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

3.

ViewTutorialBy:Raheelaat2010052521:59:38
ViewComment
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......

4.

ViewTutorialBy:vishnuchauhanat2013012411:42:16
ViewComment
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

5.

ViewTutorialBy:Pascalat2013032509:12:47
ViewComment
import gnu.io.*;
import java.io.*;

public class ListPortClass implements SerialPortEventListener


{
public static void main(String[] s)
{
http://www.javasamples.com/showtutorial.php?tutorialid=214

3/7

7/1/2015

SampleJavaprogramshowshowtowritetoCOMportusingJava.

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());
}
http://www.javasamples.com/showtutorial.php?tutorialid=214

4/7

7/1/2015

SampleJavaprogramshowshowtowritetoCOMportusingJava.

@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

6.

ViewTutorialBy:Anonymousat2013032902:39:00
ViewComment
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

7.

ViewTutorialBy:TebogoModiselleat2014103108:47:09
ViewComment

http://www.javasamples.com/showtutorial.php?tutorialid=214

5/7

7/1/2015

SampleJavaprogramshowshowtowritetoCOMportusingJava.

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.

8.

ViewTutorialBy:sanjanaat2015011706:32:41
ViewComment
no output is shown

ViewTutorialBy:shubhambansalat2015022115:36:31
Yourname(required):

Youremail(required,willnotbeshowntothepublic):

Yoursite
sURL(optional):
http://www.javasamples.com
Yourcomments:

Typethetext
Privacy&Terms

Add Your Comments

More Tutorials by Johanes

More Tutorials in Java

SampleJavaprogramshowshowtowrite
toCOMportusingJava.

Updatecontentsofafilewithinajarfile

SampleJavaprogramshowshowtoread
fromCOMportusingJava

Tomcatandhttpdconfiguredinport8080
and80
JavaFile
JavaString
Countnumberofvowels,consonantsand
digitsinaStringinJava
ReverseanumberinJava
Studentmarkscalculationprogramin
Java
HandlingFractionsinJava
CalculategrosssalaryinJava

http://www.javasamples.com/showtutorial.php?tutorialid=214

6/7

7/1/2015

SampleJavaprogramshowshowtowritetoCOMportusingJava.
CalculateaveragesaleoftheweekinJava
VectorinJavaSampleProgram
MultiLevelInheritancesampleinJava
MultipleInheritancesampleinJava
JavaprogramusingMethodOverriding
Javaprogramtocheckifuserinputisan
evennumber

MoreLatestNews

Most Viewed Articles (in Java )

Most Emailed Articles (in Java)

Countnumberofvowels,consonantsand
digitsinaStringinJava
CreatingUsersandPasswordswith
Tomcatusingtomcatusers.xml

emulator0terminatedwhilewaitingforit
toregister!

UseoftryandcatchinJava

Signingajarfileexample

HowtouseArrayListinJava

OfObject,equals(),==andhashCode()

SampleJavaprogramshowshowtowrite
toCOMportusingJava.

AbstractclassesinJava

Updatecontentsofafilewithinajarfile

MethodOverridinginJava

Tomcatandhttpdconfiguredinport8080
and80

Tomcatandhttpdconfiguredinport8080
and80

JavaFile

JavaString

JavaString

URLConnectionsampleprograminJava

ReverseanumberinJava

Howtouse'implementsRunnable'in
Java

Studentmarkscalculationprogramin
Java

UseoftryandcatchinJava

HandlingFractionsinJava

whileIterationinjava

CalculategrosssalaryinJava

Recursioninjava

CalculateaveragesaleoftheweekinJava

WhyjavaisimportanttotheInternet

VectorinJavaSampleProgram

Updatecontentsofafilewithinajarfile

instanceofsampleprograminJava

AdsbyGoogle

AdsbyGoogle

JavaDownload
Java32Bit
JavaProgramClass

JavaJar
HowtoProgramUsingJava
ArduinoJava

2014 Javasamples.com

Tutorial Archive: Android AJAX ASP.net C Cloud Computing Cocoa C++ C# EJB Java Certification Interview iPhone Javascript JSF JSP Java Beans J2ME JDBC Linux Mac OS X MySQL Perl PHP
Python Ruby VB.net Struts Test Papers Trends SAP WebServices XML Office 365 Hibernate
Latest Tutorials on: Android AJAX ASP.net C Cocoa Cloud Computing C++ C# EJB Java Certification Interview iPhone JavaScript JSF JSP Java Beans J2ME JDBC Linux Mac OS X MySQL Perl
PHP Python Ruby VB.net SAP Struts Trends WebServices XML Office 365 Hibernate

http://www.javasamples.com/showtutorial.php?tutorialid=214

7/7

S-ar putea să vă placă și