我在网上找了很多的串口通讯的东西,结果都是一样的,都是互相抄袭,
解决不了问题,我这里提示找不到端口,用其他的工具可以测试到com1
大侠们,帮帮忙吧。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