2012-03-31 62 views
1

我有一個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 
} 
} 

和傳播者類別(在不同文件中的不同類別)是

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"); 

    } 

}    
} 
+0

看起來像您嘗試使用的COM端口很忙。嘗試使用不同的串行端口,直到您知道它未被使用。 – asgs 2012-03-31 14:09:39

回答

2

它看起來像這樣:

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

拋出一個異常,這可能意味着serialPort仍然是行後空因爲調用open失敗。

然後你有下面這行的下一個try塊,這將拋出一個NPE如果serialPort是空的:

inputStream = serialPort.getInputStream(); 

這將讓您的生活更容易,如果你只在有一個try/catch塊ListenOnPort方法,而不是3

注:在Java方法名稱通常開始以小寫:ListenOnPort =>listenOnPort

0

你得到三個異常消息:

Port COM10 not found. 

此消息產生於getPort()。從該方法返回後,可能portId仍然爲空。

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

此消息在ListenOnPort()的第一個嘗試塊中生成。查看該消息的結尾「java.lang.NullPointerException」。這支持portId ist null的聲明。

Exception in thread "main" java.lang.NullPointerException 

現在由assylias指出,呼叫serialPort.getInputStream()失敗,因爲serialPort爲空,太。

我建議你改進錯誤報告,例如用e.printStackTrace()而不是System.err.println("Ex")打印消息和堆棧跟蹤例外情況。

+0

與錯誤報告一致,雖然將其記錄到文件或DB中比在err或out控制檯上打印異常堆棧記錄更好。 – asgs 2012-03-31 14:08:12

+0

當然是。使用適當的日誌框架,可以在不更改程序的情況下配置日誌消息目標。 – 2012-03-31 16:38:19