Java reads and writes serial port

xiaoxiao2021-03-06  41

The serial read and write package download address under Linux:

http://to.agreatserver.com/rxtx21.zip

The Win32 platform can be downloaded from the Sun's website.

Below is an example

//Serialtest.java

// by aico

// 2004-05-11

Import java.io. *;

Import java.util. *;

Import gnu.io. *;

Public Class Serialtest

{

Public static void main (string [] args)

{

String commname = "com1"; // for Win32

// String Commname = "/ dev / ttys0"; // for Linux

SerialTest ST = New SerialTest ();

SerialPort Port = St.getSerialPort (Commname);

IF (port! = NULL)

{

St.writeString (Port, "Hi, Serial Test.");

Port.close ();

}

}

Public SerialPort GetSerialPort (String Commname)

{

IF (COMMNAME == NULL)

Return NULL;

Enumeration portlist = commportidentifier.getportidentifiers ();

While (portlist.hasmorelements ())

{

CommPortidentifier portid = (CommPortIndIfier) ​​PortList.nexTelement ();

IF ((Portid.getPortType () == Commportidentifier.port_serial) && portid.getname (). EqualsignoreCase (Commname))

{

SerialPort Port = NULL;

Try

{

Port = (SerialPort) Portid.open ("Test", 2000);

} catch (portinuseexception e)

{

E.PrintStackTrace ();

}

Return port;

}

}

Return NULL;

}

Public void Writestring (SerialPort Port, String Message)

{

IF (port == null | | message == null)

Return;

OutputStream out = null;

Try

{

OUT = port.getOutputStream ();

} Catch (ioException e)

{

E.PrintStackTrace ();

Return;

}

Try

{

Port.setserialportParams (9600, SerialPort.Database_8, serialport.stopbits_1, serialport.parity_none);

} Catch (unsupportedcommoperationexception e)

{

E.PrintStackTrace ();

Return;

}

Try

{

Out.write (Message.GetBytes ());

} Catch (ioexception e) {

E.PrintStackTrace ();

Return;

}

}

}

-------------------------------------------------- -------------

Maybe help you:

http://www-900.ibm.com/developerWorks/cn/java/joy-comm/index.shtml

转载请注明原文地址:https://www.9cbs.com/read-71921.html

New Post(0)