如何使用comm.jar和Netbeans 6.8列出可用端口?

时间:2011-01-12 20:44:10

标签: java netbeans

我正在尝试使用以下代码显示计算机中的可用端口..

public static void test(){

    Enumeration lists=CommPortIdentifier.getPortIdentifiers();
        System.out.println(CommPortIdentifier.PORT_SERIAL);
        System.out.println(lists.hasMoreElements());
        while (lists.hasMoreElements()){
            CommPortIdentifier cn=(CommPortIdentifier)lists.nextElement();

            if ((CommPortIdentifier.PORT_SERIAL==cn.getPortType())){
                System.out.println("Name is serail portzzzz "+cn.getName()+" Owned status "+cn.isCurrentlyOwned());

                try{
                    SerialPort port1=(SerialPort)cn.open("ComControl",800000);
                    port1.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
                    System.out.println("Before get stream");
                    OutputStream out=port1.getOutputStream();
                    InputStream input=port1.getInputStream();
                    System.out.println("Before write");
                    out.write("AT".getBytes());
                    System.out.println("After write");
                    int sample=0;
                    //while((( sample=input.read())!=-1)){
                    System.out.println("Before read");
                        //System.out.println(input.read() + "TEsting ");
                    //}
                        System.out.println("After read");
                    System.out.println("Receive timeout is "+port1.getReceiveTimeout());
                }catch(Exception e){
                    System.err.println(e.getMessage());
                }
            }

            else{
                System.out.println("Name is parallel portzzzz "+cn.getName()+" Owned status "+cn.isCurrentlyOwned()+cn.getPortType()+"    ");
            }
        }

}

我的输出始终是;

1 假

虽然没有循环(lists.hasMoreElements()){

/// )

可能出现的问题是什么?

1 个答案:

答案 0 :(得分:2)

你错过了司机:

String driverName = "com.sun.comm.Win32Driver";
CommDriver commdriver =
(CommDriver) Class.forName(driverName).newInstance();
commdriver.initialize();

让我们知道您是否需要更多代码,或者这足以让您入门。

或者

在您的类路径中包含此文件javax.comm.properties 有了这个内容: Driver=com.sun.comm.Win32Driver