CommPortIdentifier 中open()方法乍么没有法返回串口
萧三皮 2010-07-07 01:44:39 mport java.io.*;
import java.util.*;
import javax.comm.*;
public class SimpleWrite {
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("COM1")) {
try {
System.out.println(portId);
serialPort = (SerialPort)
portId.open("SimpleWriteApp", 2000);
} catch (PortInUseException e) {
e.printStackTrace();
}
try {
outputStream = serialPort.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}
try {
outputStream.write(messageString.getBytes());
} catch (IOException e) {}
}
}
}
}
}
javax.comm.CommPortIdentifier@276af2
javax.comm.PortInUseException: Port currently owned by SimpleWriteApp
at javax.comm.CommPortIdentifier.open(CommPortIdentifier.java:337)
at Simple.SimpleWrite.main(SimpleWrite.java:55)
Exception in thread "main" java.lang.NullPointerException
at Simple.SimpleWrite.main(SimpleWrite.java:61)