嗨,我有这样的东西
package compot;
import java.util.Enumeration;
import gnu.io.*;
public class core {
private static SerialPort p;
/**
* @param args
*/
public static void main(String[] args)
{
Enumeration ports = CommPortIdentifier.getPortIdentifiers();
System.out.println("start");
while(ports.hasMoreElements())
{
CommPortIdentifier port = (CommPortIdentifier) ports.nextElement();
System.out.print(port.getName() + " -> " + port.getCurrentOwner() + " -> ");
switch(port.getPortType())
{
case CommPortIdentifier.PORT_PARALLEL:
System.out.println("parell");
break;
case CommPortIdentifier.PORT_SERIAL:
//System.out.println("serial");
try {
p = (SerialPort) port.open("core", 1000);
int baudRate = 57600; // 57600bps
p.setSerialPortParams(
baudRate,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (PortInUseException e) {
System.out.println(e.getMessage());
} catch (UnsupportedCommOperationException e) {
System.out.println(e.getMessage());
}
break;
}
}
System.out.println("stop");
}
}但是我不知道怎么从端口读??我读过本教程,但我不知道它们是什么意思??
编辑
OutputStream outStream = p.getOutputStream();
InputStream inStream = p.getInputStream();
BufferedReader in = new BufferedReader( new InputStreamReader(inStream));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();我已经添加了这个代码,但是我增加了
稳定库=========================================本机库版本= RXTX-2.1-7 Java版本= RXTX-2.1-7开始/dev/ttyUSB3 3 ->空->基础输入流返回零字节停止
发布于 2011-07-20 12:15:18
这是你的密码吗?你到底想在那里做什么?
为了从SerialPort中读取数据,需要声明以下端口:
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("/dev/tty/USB0"); //on unix based system然后在这个端口上打开一个连接:
SerialPort serialPort = (SerialPort) portIdentifier.open("NameOfConnection-whatever", 0);下一步将是设置该端口的参数(如果需要的话):
serialPort.setSerialPortParams(38400, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);这是我的配置--您的配置可能因此不同:)
现在,您已经准备好读取该端口上的一些数据了!要获取数据,需要获取serialPorts输入流并从中读取:
InputStream inputStream = serialPort.getInputStream();
while (active) {
try {
byte[] buffer = new byte[22];
while ((buffer[0] = (byte) inputStream.read()) != 'R') {
}
int i = 1;
while (i < 22) {
if (!active) {
break;
}
buffer[i++] = (byte) inputStream.read();
}
//do with the buffer whatever you want!
} catch (IOException ex) {
logger.error(ex.getMessage(), ex);
}
}实际上,我在这里所做的是使用read()方法从输入流中读取数据。这将阻塞,直到数据可用或返回-1,如果到达流的结束。在本例中,我一直等到得到一个'R‘字符,然后将接下来的22个字节读入缓冲区。这就是你读取数据的方式。
active可以通过另一种方法设置为false,从而结束读取过程。希望这能帮上忙
发布于 2011-10-07 10:15:05
试着使用
if (socketReader.ready()) {
}因此,只有当缓冲区流中有需要读取的内容时,套接字才会做出响应,这样就不会发生异常。
发布于 2011-07-20 12:13:11
在您的尝试块中,类似这样的内容:
OutputStream outStream = p.getOutputStream();
InputStream inStream = p.getInputStream();https://stackoverflow.com/questions/6761572
复制相似问题