Java CommPortIdentifier.getPortIdentifiers() 返回 null Windows 7

标签 java serial-port

我试图从我的电脑串行端口读取数据,但我不断收到一组空端口。我在 stackoverflow、coderanch 和 oracle 论坛上查找了许多其他问题,所有这些问题都提到需要将 win32com.dll、comm.jar 和 javax.comm.properties 放在 jre 文件夹中的特定目录中。完成所有这些操作后,我仍然得到一组空端口。这是我的代码(几乎是从网上复制和粘贴的):

import java.io.*;
import java.util.*;

import javax.comm.*;



public class ReadWriteSerial implements SerialPortEventListener{

    private Enumeration portList = null;
    private CommPortIdentifier portId = null;
    private String defaultPort = null;
    private boolean portFound = false;
    private int baudRate = 0;
    private SerialPort serialPort = null;
    private DataInputStream is = null;
    private BufferedReader inStream;



    /********************************
     * Constructor for the base class
     * @param defaultPort
     * @param baudrate
     *******************************/
    public ReadWriteSerial(String defaultPort, int baudrate) throws NoSuchPortException{

        this.defaultPort = defaultPort;
        checkPorts();                     // Call a method for checking ports on the System

    }


    /************************************
     * This method checks the presence of
     * ports on the System, in affirmative
     * case initializes and configures it
     * to receive data on the serial port
     ***********************************/

    public void checkPorts() throws NoSuchPortException{

        /***************************************
         * Get a list of all ports on the system
         **************************************/
      //  CommPortIdentifier d = CommPortIdentifier.getPortIdentifier("COM1");
        portList =CommPortIdentifier.getPortIdentifiers();
        System.out.println("List of all serial ports on this system:");

        while(portList.hasMoreElements()){
            portId = (CommPortIdentifier)portList.nextElement();
            if(portId.getName().equals(defaultPort)){
                portFound = true;
                System.out.println("Port found on: " + defaultPort);

                initialize();       // If Port found then initialize the port

            }   
        }

        if(!portFound){
            System.out.println("No serial port found!!!");
        }
    }

    public void initialize(){
        /**********************
         * Open the serial port
         *********************/
        try{
            serialPort = (SerialPort)portId.open("Artificial Horizont", 2000);
        } catch (PortInUseException ex){
            System.err.println("Port already in use!");
        }

        // Get input stream
        try{
            is = new DataInputStream(serialPort.getInputStream());
        } catch (IOException e){
            System.err.println("Cannot open Input Stream " + e);
            is = null;
        }


        try{
            serialPort.setSerialPortParams(this.baudRate,
                                           SerialPort.DATABITS_8,
                                           SerialPort.STOPBITS_1,
                                           SerialPort.PARITY_NONE);
        } catch (UnsupportedCommOperationException ex){
            System.err.println("Wrong settings for the serial port: " + ex.getMessage());
        }


        try{
            serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
        } catch (UnsupportedCommOperationException ex){
            System.err.println("Check the flow control setting: " + ex.getMessage());
        }

        // Add an event Listener
        try{
            serialPort.addEventListener(this);
        } catch (TooManyListenersException ev){
            System.err.println("Too many Listeners! " + ev);
        }

        // Advise if data available to be read on the port
        serialPort.notifyOnDataAvailable(true);
    }


    /**********************************
     * Method from interface definition
     * @param event
     *********************************/
    @Override
    public void serialEvent(SerialPortEvent event){

        inStream = new BufferedReader(new InputStreamReader(is), 5);
        String rawInput = null;

        switch(event.getEventType()){
        case SerialPortEvent.BI:
        case SerialPortEvent.CD:
        case SerialPortEvent.CTS:
        case SerialPortEvent.DSR:
        case SerialPortEvent.FE:
        case SerialPortEvent.OE:
        case SerialPortEvent.PE:
        case SerialPortEvent.RI:
        case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
            break;

        case SerialPortEvent.DATA_AVAILABLE:
            try {
                while((rawInput = inStream.readLine()) != null){
                    System.out.println(rawInput);
/*
!!!!!!!!!!!!!!!!!!!!!!!!!!!!HERE I GET THE VALUE FROM THE SERIAL PORT AND THOSE MUST BE "VISIBLE" TO THE SUBPANEL CLASS IN ORDER AND RUN THE METHOD REPAINT!!!!!!!!!!!!!!!!!!!!!
*/
                }

                inStream.close();

            } catch (IOException e) {
                e.printStackTrace();
                System.exit(-1);
            }
            break;

        default:
            break;

        }
    }

}

和我的主课:

public class RunComReader {
    public static void main(String[] args) throws NoSuchPortException {
        ReadWriteSerial reader = new ReadWriteSerial("COM1", 2000);
    }
}

这些文件放置在该目录的 lib、bin 和 lib/ext 文件夹中:

C:\Program Files (x86)\Java\jre1.8.0_31

我做错了什么?

最佳答案

Java 8 不再支持 javax.com lib。 您可以使用 jssc lib ( https://code.google.com/p/java-simple-serial-connector/ ) 进行串行通信。

关于Java CommPortIdentifier.getPortIdentifiers() 返回 null Windows 7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30268797/

相关文章:

java - Java 中 Mac 上的 JTable 中的 JTooltip 在单击时不会选择该行

java - Java 中的 Diffie-Hellman key 交换

Android连接BLE模块并通过串口发送数据

linux - 有时串口读取给出转换后的值[垃圾值]

java - 如何在 Android 中以编程方式更改菜单标题

java - 在java中使用嵌套循环解决消除问题?

java - 如何使用通用图像加载器在 ImageView 中设置图像适合 XY 而不会划伤?

c++ - 读取 USB 串行数据时出现问题

java - 无法检测到蓝牙服务(java.lang.NumberFormatException : For input string: "0S" )

java - 这是 ASCII 类型吗?