空指针访问串行端口时出现异常

时间:2012-03-31 12:53:35

标签: java serial-port nullpointerexception

我有一个Java项目(在NetBeans 7.1中),我收到以下NullPointerException

run:
Port COM10 not found.
The serial port you are trying to use is currently in usejava.lang.NullPointerException
Exception in thread "main" java.lang.NullPointerException
    at mateorssms.Communicator.ListenOnPort(Communicator.java:68)
    at mateorssms.Communicator.<init>(Communicator.java:35)
    at mateorssms.MateorsSMS.main(MateorsSMS.java:14)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second).

所以我的MateorsSMS课程是:

package mateorssms;

import java.awt.Frame;


public class MateorsSMS{    
public static void main(String[] args) {
    //UserInterface UI = new UserInterface();
    //UI.setVisible(true);
    new Communicator();        
    // TODO code application logic here
}
}

和Communicator类(不同文件中的不同类)是

package mateorssms;

import java.io.IOException;
import java.io.InputStream;
import javax.comm.*;
import java.util.Enumeration;
import java.util.TooManyListenersException;


public class Communicator implements Runnable, SerialPortEventListener{

static Enumeration portList;
static CommPortIdentifier portId;
boolean portFound = false;    
SerialPort serialPort;
String defaultPort = "COM10"; 
Thread readThread;
InputStream inputStream;



public Communicator(){
    getPort();  
    ListenOnPort();
}




private void getPort(){  //////////////////////////////////////////////////////////////////////////////
    portFound = false;
    portList = CommPortIdentifier.getPortIdentifiers();
    while(portList.hasMoreElements() && !(portFound)){
        portId = (CommPortIdentifier) portList.nextElement();
        if(portId.getPortType() == CommPortIdentifier.PORT_SERIAL){
            if(portId.getName().equals(defaultPort)){
                System.out.println("Found port: " + defaultPort);
                portFound = true;
            }
        }
    }
    if(!portFound){
        System.err.println("Port " + defaultPort + " not found."); //user feedback
        //System.exit(1);            
    }
}

private void ListenOnPort(){
    try {
        serialPort = (SerialPort) portId.open("MateorsSMSApp", 300);
        System.out.println("yes");
    } catch (Exception e) {
        System.out.println("The serial port you are trying to use is currently in use"+e.toString());
    }

    try {
        inputStream = serialPort.getInputStream();
        System.out.println(inputStream.toString());
    } catch (IOException e) {
        System.err.println("Ex");
    }
    try {
        serialPort.addEventListener(this);
    } catch (TooManyListenersException e) {
        System.err.println("Ex");
    }
    // activate the DATA_AVAILABLE notifier
    serialPort.notifyOnDataAvailable(true);
    try {           
        serialPort.setSerialPortParams(460800,
                SerialPort.DATABITS_8,
                SerialPort.STOPBITS_1,
                SerialPort.PARITY_NONE);
        serialPort.setDTR(true);
        serialPort.setRTS(true);
    } catch (UnsupportedCommOperationException e) {
        System.err.println("Ex");
    }

    readThread = new Thread(this);
    readThread.start();
}



@Override
public void serialEvent(SerialPortEvent event) {
    switch (event.getEventType()) {
        case SerialPortEvent.BI: System.out.println("BI"); // Break interruptbreak;
        case SerialPortEvent.OE: System.out.println("OE");// Overrun error break;
        case SerialPortEvent.FE: System.out.println("FE");// Framing error break;
        case SerialPortEvent.PE: System.out.println("PE");// Parity error break;
        case SerialPortEvent.CD: System.out.println("CD");//Carrier detected break;
        case SerialPortEvent.CTS: System.out.println("CTS");//Clear to send break;
        case SerialPortEvent.DSR: System.out.println("DSR");// Data set ready break;
        case SerialPortEvent.RI: System.out.println("RI");// Ring indicator break;
        case SerialPortEvent.OUTPUT_BUFFER_EMPTY: System.out.println("OUTPUT_BUFFER_EMPTY"); //break;
        //break; //Buffer empty

        case SerialPortEvent.DATA_AVAILABLE: //Data Available to be read

            System.out.println("DATA_AVAILABLE");
            byte[] readBuffer = new byte[20]; 

            try {

                while (inputStream.available() > 0) {
                    int numBytes = inputStream.read(readBuffer);
                }

                String result = new String(readBuffer);
                System.out.println(result);
            } catch (IOException e) {
                System.err.println("Ex");
            }
            break;
    }
    //SerialPort port;
    // TODO do something with ev
}


@Override
public void run(){
    try {
        Thread.sleep(3000);
    } catch (InterruptedException ex){
        System.err.println("Ex");

    }

}            
}

2 个答案:

答案 0 :(得分:2)

看起来像这一行:

serialPort = (SerialPort) portId.open("MateorsSMSApp", 300);

抛出异常,这可能意味着serialPort在该行之后仍为空,因为对open的调用失败。

然后在下一个try块中,您有以下行,如果serialPort为null,则会抛出NPE:

inputStream = serialPort.getInputStream();

如果您在ListenOnPort方法中只有一个try / catch块而不是3,那么这会让您的生活更轻松。

注意:Java中的方法名称通常以小写字母开头:ListenOnPort =&gt; listenOnPort

答案 1 :(得分:0)

您收到三条异常消息:

Port COM10 not found.

此消息在getPort()中生成。从该方法返回后,portId可能仍然为空。

The serial port you are trying to use is currently in usejava.lang.NullPointerException

此消息在ListenOnPort()的第一个try块中生成。请参阅该消息的结尾“java.lang.NullPointerException”。这支持portId为空的声明。

Exception in thread "main" java.lang.NullPointerException

现在如assylias所述,调用serialPort.getInputStream()失败,因为serialPort也为空。

我建议您改进错误报告,例如使用e.printStackTrace()代替System.err.println("Ex")打印消息和堆栈异常跟踪。

相关问题