javaComm20-win32你操作comm的需要的资料和相关的配置文件,相关的配置方法如(javaComm20-win32的里面也有相关的介绍):把win32com.dll复制到java.home/bin下;把javax.comm.properties复制到java.home/lib下;把comm.jar添加到你classPath下。前面两个都是非常重要的。
Java,comm是专门为Java读取串口信息的而编写的API,这个既可以读取到串口的信息,也可以进行相关数据的写入到对应的串口中。这个一般刚刚开始,使用简单的代码,进行读取的时候,可能会什么都没有发现,这个是应该,你的代码的问题,网上有的人说是,电脑配置了这个环境,机器要重新的启动,但是我测试了,这个是不对的。这个是代码的问题导致的。看看下面的代码,这个代码的下载的文件中自带的测试的代码:
就这样,进行pc的信息的获取,那么可能什么信息都获取不到啊。我想这个可能的原因是:win32com.dll中相关的需要的信息,没有读取到,没有进行相关的驱动的加载,所以什么读取不到。将/**/中,代码加入,那么就能读取到相关的串口的信息了。
import java.io.*; import java.util.*; import javax.comm.*; public class SimpleRead implements Runnable, SerialPortEventListener { static CommPortIdentifier portId; static Enumeration portList; InputStream inputStream; SerialPort serialPort; Thread readThread; public static void main(String[] args) { /*CommDriver driver = null; String driverName = "com.sun.comm.Win32Driver"; try { driver = (CommDriver) Class.forName(driverName).newInstance(); driver.initialize(); } catch (InstantiationException e){ e.printStackTrace(); } catch (IllegalAccessException e){ e.printStackTrace(); } catch (ClassNotFoundException e){ e.printStackTrace(); }*/ portList = CommPortIdentifier.getPortIdentifiers(); System.out.println("flag:"+portList.hasMoreElements()); while (portList.hasMoreElements()) { portId = (CommPortIdentifier) portList.nextElement(); if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { if (portId.getName().equals("COM1")) { SimpleRead reader = new SimpleRead(); } } } } public SimpleRead() { try { serialPort = (SerialPort) portId.open("SimpleReadApp", 2000); } catch (PortInUseException e) { e.printStackTrace(); } try { inputStream = serialPort.getInputStream(); } catch (IOException e) { e.printStackTrace(); } try { serialPort.addEventListener(this); } catch (TooManyListenersException e) { e.printStackTrace(); } serialPort.notifyOnDataAvailable(true); try { serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); } catch (UnsupportedCommOperationException e) { e.printStackTrace(); } readThread = new Thread(this); readThread.start(); } public void run() { try { Thread.sleep(20000); } catch (InterruptedException e) { e.printStackTrace(); } } public void serialEvent(SerialPortEvent event) { switch(event.getEventType()) { case SerialPortEvent.BI: case SerialPortEvent.OE: case SerialPortEvent.FE: case SerialPortEvent.PE: case SerialPortEvent.CD: case SerialPortEvent.CTS: case SerialPortEvent.DSR: case SerialPortEvent.RI: case SerialPortEvent.OUTPUT_BUFFER_EMPTY: break; case SerialPortEvent.DATA_AVAILABLE: byte[] readBuffer = new byte[20]; try { while (inputStream.available() > 0) { int numBytes = inputStream.read(readBuffer); } System.out.print(new String(readBuffer)); } catch (IOException e) { e.printStackTrace(); } break; } } }