主要参考了这里:http://www.cnblogs.com/jiandanfy/archive/2009/03/23/1419373.html
先要下载串口包:http://mdubuc.freeshell.org/Jolt/javacomm20-win32.zip
里面有三个文件要放在指定位置
win32comm.dll,经测试可以放在jdk/bin或jre/bin或windows/system32下均可
comm.jar和javax.comm.properties,我是一起放在jre/lib下的。我的环境里,一起放jre/lib/ext,jdk/jre/lib,jdk/jre/lib/ext,jdk/lib/ext下都不行。会找不到串口
下面是最简单的代码,加上log或print可以显示是否找到串口以验证环境配置
import java.io.*;
import java.util.*;
import javax.comm.*;
public class TestComm
{
@SuppressWarnings("rawtypes")
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("COM2"))
{
// 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)
{}
}
}
}
}
}
}
其实是个非常简单的问题,就是因为不知道包该放在哪里而变得复杂,网上众说纷纭,我不得已把包放得到处都是直到好用又一个个删掉才确定我的环境下到底该怎么配...
whatever, first step is done...