解决不了问题,我这里提示找不到端口,用其他的工具可以测试到com1
大侠们,帮帮忙吧。
- Java code
- import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import javax.comm.CommPortIdentifier; import javax.comm.NoSuchPortException; import javax.comm.PortInUseException; import javax.comm.SerialPort; import javax.comm.UnsupportedCommOperationException; /** * * This bean provides some basic functions to implement full dulplex information * exchange through the srial port. * */ public class SerialBean { static String PortName; CommPortIdentifier portId; SerialPort serialPort; static OutputStream out; static InputStream in; SerialBuffer SB; ReadSerial RT; /**//* 这个方法是SerialBean的构造函数,参数port表示COM口,1:COM1,2:COM2, 以此类推。在这个类中设置了COM口名:portName。portName必须是这种格式,因为getPortIdentifier方法要使用它 */ public SerialBean(int PortID) { PortName = "COM" + PortID; } public int Initialize() { int InitSuccess = 1; int InitFail = -1; try { // 根据portName得到COM的标识对象 System.out.println(PortName); portId = CommPortIdentifier.getPortIdentifier(PortName); try { // 打开COM口, open方法的第二个参数是超时时间,单位是毫秒。 // 在本程序中超时时间是5秒 serialPort = (SerialPort) portId.open("Serial_Communication",10000); } catch (PortInUseException e) { return InitFail; } try { // 下面是得到用于和COM口通讯的输入、输出流。 in = serialPort.getInputStream(); out = serialPort.getOutputStream(); } catch (IOException e) { return InitFail; } try { // 下面是初始化COM口的传输参数,如传输速率:9600等。 serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); System.out.println("初始化串口成功"); } catch (UnsupportedCommOperationException e) { System.out.println("初始化串口失败"); return InitFail; } } catch (NoSuchPortException e) { System.out.println("没有此端口"); return InitFail; } // 当上面的代码执行成功后,将建立一个数据缓冲区,然后启动 // 一个线程,用于接收从COM 口传回的数据 SB = new SerialBuffer(); RT = new ReadSerial(SB, in); RT.start(); return InitSuccess; } // 这个方法从COM口读出length个字符 public String ReadPort(int Length) { String Msg; Msg = SB.GetMsg(Length); return Msg; } // 这个函数向COM口写入一个字符串 public void WritePort(String Msg) { try { for (int i = 0; i < Msg.length(); i++) out.write(Msg.charAt(i)); } catch (IOException e) { } } // 关闭正在使用的COM口 public void ClosePort() { RT.stop(); serialPort.close(); } public static void main(String[] args){ Enumeration portList=CommPortIdentifier.getPortIdentifiers(); System.out.println(portList.hasMoreElements()); while(portList.hasMoreElements()){ System.out.println(portList.nextElement()); } // SerialBean sb = new SerialBean(1); // System.out.println(sb.Initialize()); } }数据挖掘研究院
初始化串口失败javax.comm.NoSuchPortException
做商品编程有几点要注意:
你要的端口有,二是防火啬之类的东西的影响要注意.
防火墙在端口相关操作时很有影响,有些看似没有拦,实际是不让检测.通讯问题已经解决,
http://topic.csdn.net/u/20071226/15/29029821-178a-47cf-92dd-9d19d2f6b978.html
但是现在有新的问题,只能写入,也能读出,但是只能有8位
其他的数据读不出来。很是郁闷
編程王網站www.kingofcoder.com楼主做个循环输出就可以了,截取为8位,然后输出

