Java串口问题

主要参考了这里: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...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值