日期:2014-05-20  浏览次数:20802 次

怎样用java清空串口的输入缓冲区?
哪位兄弟知道怎样用java清空串口的输入缓冲区?
网上c/c++这方面的资料比较多,java一个也没有找到.

------解决方案--------------------
不知道具体串口的细节,因为java一般不直接操作底层的东西,java处理串口一般是jni,找javax.comm,或者rxtx,这些都实现得不错。
------解决方案--------------------
不懂对地层的操作,好象这不是java的专长吧
------解决方案--------------------
我也查资料作了一个,但是也有问题,连续发送数据有时会被截断,把代码发上来大家研究一下
import java.io.*;
import java.util.*;
import javax.comm.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/**
*
* @author tian
*/
public class ComTest {

/** Creates a new instance of ComTest */
public ComTest() {
com c=new com();
c.setTitle( "串口测试 ");
c.setSize(400,400);
c.setResizable(false);
c.setVisible(true);
Dimension screen=Toolkit.getDefaultToolkit().getScreenSize();
c.setLocation((screen.width-400)/2,(screen.height-400)/2);
}
public static void main(String[]args){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

}
catch (Exception exception) {
exception.printStackTrace();
}
new ComTest();
}
});
}
}
class com extends JFrame implements ActionListener,SerialPortEventListener{
static Enumeration portList;//枚举类型
static CommPortIdentifier portId;/* 检测系统中可用的通讯端口类 */
static SerialPort serialPort;/* 声明RS-232串行端口的成员变量 */
static OutputStream outputStream;//输出流
static InputStream inputStream;//输入流
static boolean use=false;
static boolean flag=true;
JPanel panel;
JScrollPane scrollPane;
JTextField text=new JTextField();
JButton button1=new JButton( "发送 ");
JButton button2=new JButton( "自动发送 ");
JButton button3=new JButton( "清除 ");
JTextArea area=new JTextArea();
JLabel label=new JLabel( "手动发送 ");
String message;
com(){
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
jbInt();
}
public void jbInt(){
panel=(JPanel)getContentPane();
panel.setLayout(null);
scrollPane=new JScrollPane(area);
label.setBounds(35,30,100,25);
text.setBounds(120,30,150,25);
button1.setBounds(290,30,80,23);
button2.setBounds(160,335,80,25);
button3.setBounds(280,335,80,25);
scrollPane.setBounds(35,70,340,250);
area.setFont(new Font( " ",Font.PLAIN,14));//设置字体大小
panel.add(label);
panel.add(text);
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(scrollPane);
button1.addActionListener(this);//添加监听
button2.addActionListener(this);
button3.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button1)
{
message=text.getText();//将text中的文本赋予message

if(message.length()> 0)//判断message是否为空
{
System.out.println(message);
a(); //调用方法放
}