最近了解到的需求是需要需激光打刻機進行(RS
之前並沒有用java做過串口通信
項目實際應用中可能會采用VB開發(這個我就不會了)
只不過用java嘗試一下
下面是實現代碼
Java代碼
package test;
import java
import java
import java
import java
import java
import java
import java
import gnu
import gnu
import gnu
import gnu
import gnu
import gnu
public class CommUtil implements SerialPortEventListener {
InputStream inputStream; // 從串口來的輸入流
OutputStream outputStream;// 向串口輸出的流
SerialPort serialPort; // 串口的引用
CommPortIdentifier portId;
public CommUtil(Enumeration portList
while (portList
CommPortIdentifier temp = (CommPortIdentifier) portList
if (temp
if (temp
portId = temp;
}
}
}
try {
serialPort = (SerialPort) portId
} catch (PortInUseException e) {
}
try {
inputStream = serialPort
outputStream = serialPort
} catch (IOException e) {
}
try {
serialPort
} catch (TooManyListenersException e) {
}
serialPort
try {
serialPort
SerialPort
} catch (UnsupportedCommOperationException e) {
}
}
public void serialEvent(SerialPortEvent event) {
switch (event
case SerialPortEvent
case SerialPortEvent
case SerialPortEvent
case SerialPortEvent
case SerialPortEvent
case SerialPortEvent
case SerialPortEvent
case SerialPortEvent
case SerialPortEvent
break;
case SerialPortEvent
byte[] readBuffer = new byte[
try {
while (inputStream
System
int numBytes = inputStream
System
}
System
} catch (IOException e) {
e
}
break;
}
}
public void send(String content){
try {
outputStream
} catch (IOException e) {
e
}
}
public void ClosePort() {
if (serialPort != null) {
serialPort
}
}
}
測試
Java代碼
package test;
import gnu
import java
public class Test {
public static void main(String[] args) throws InterruptedException {
Enumeration portList = CommPortIdentifier
CommUtil comm
int i =
while(i<
{
Thread
comm
i++;
}
comm
}
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/25965.html