public synchronized void serialEvent(SerialPortEvent ev) { DataInputStream in;
int c = 0;
StringBuffer sb = null;
String str = "";
// 如果有串口事件发生
if (ev.getEventType() == SerialPortEvent.DATA_AVAILABLE)
{
try {
in = new DataInputStream(sPort.getInputStream());
sb = new StringBuffer();
while ((c = in.read()) != -1) {
sb.append((char) c);
System.out.println(sb);
}
str= new String(sb.toString());
System.out.println(str);
} catch (IOException e) { ;
e.printStackTrace();
}
System.out.println("kangbingyingxiong");
}
} 请问上面的代码 有什么问题吗?
请问该 System.out.println("kangbingyingxiong");代码 为何不执行; 我要实现的目的就是 把串口的数据 读入到一个string对象中 就是实现不了 困扰我很久了 请各位帮忙 谢谢
int c = 0;
StringBuffer sb = null;
String str = "";
// 如果有串口事件发生
if (ev.getEventType() == SerialPortEvent.DATA_AVAILABLE)
{
try {
in = new DataInputStream(sPort.getInputStream());
sb = new StringBuffer();
while ((c = in.read()) != -1) {
sb.append((char) c);
System.out.println(sb);
}
str= new String(sb.toString());
System.out.println(str);
} catch (IOException e) { ;
e.printStackTrace();
}
System.out.println("kangbingyingxiong");
}
} 请问上面的代码 有什么问题吗?
请问该 System.out.println("kangbingyingxiong");代码 为何不执行; 我要实现的目的就是 把串口的数据 读入到一个string对象中 就是实现不了 困扰我很久了 请各位帮忙 谢谢
这样还多生成了一个对象 直接str= sb.toString();
如要对端口监听,你必须先取得CommPortIdentifier类的一个实例, CommPort serialPort = portId.open("My App", 60); 从而取得SerialPort,再调用它的addEventListener方法为它添加监听器, serialPort.addEventListener(new MyPortListener());
但只有一个可以打印出来!
后面的一个不打印!就是System.out.println("kangbingyingxiong"); 根本上不执行!
我调试了很多遍 !只有while循环里面才可以打印初来!
kengking 兄的 我已经实现了 ! 现在问题是
代码 部分不执行!
System.out.println(sb); //在while循环内
System.out.println(str);
System.out.println("kangbingyingxiong"); 你上面说“但只有一个可以打印出来!只有while循环里面才可以打印初来! ” 那就是说一直在while循环?1. 如果问题是因为一直停留在while循环,那改成>0试试看:
while ((c = in.read()) > 0) { 2. 如果第二个打印也出来了(System.out.println(str); ) ,那可能是编译后缓存的问题,把所有的classes文件删除,清除所有可能存在的缓存,然后重新编译,再调试看看。
System.out.println(str);
System.out.println("kangbingyingxiong"); 只有第一个可以打印出来 其它两个都不可以打印!即使 System.out.println("test"); 一样不可以打印!就好像是 while后面的语句都不执行了一样!按7楼做了 还是一样 !
String str = null;
// 如果有串口事件发生
if (ev.getEventType() == SerialPortEvent.DATA_AVAILABLE)
{
try {
InputStream in = sPort.getInputStream();
while(in.available() > 0 ) {
bos.write( in.read() );
System.out.println(bos);
}
str= bos.toString();
System.out.println(str);
} catch (IOException e) { ;
e.printStackTrace();
}
System.out.println("kangbingyingxiong");
}
}
更快的版本为:
public synchronized void serialEvent(SerialPortEvent ev) { ByteArrayOutputStream bos = new ByteArrayOutputStream();
String str = null;
// 如果有串口事件发生
if (ev.getEventType() == SerialPortEvent.DATA_AVAILABLE)
{
try {
InputStream in = sPort.getInputStream();
byte[] buf = new byte[16];
while(in.available() > 0 ) {
int bytes_read = in.read( buf );
if( bytes_read > 0 ) {
bos.write( buf, 0, bytes_read );
}else {
break;
}
System.out.println(bos);
}
str= bos.toString();
System.out.println(str);
} catch (IOException e) { ;
e.printStackTrace();
}
System.out.println("kangbingyingxiong");
}
}