在没有侦听器事件的情况下从java中的串行端口读取和写入

时间:2014-12-15 05:21:00

标签: java nullpointerexception inputstream

我想从串口读取字节并按顺序写入。有什么方法可以通过在java中创建两个独立的读写函数来读取/写入串口?我写了一个程序但是在这里,即使打开了所需的COM端口,serialPort.getInputStream()也会给出一个空指针异常。

这是我的代码

        package PhyCom;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.TooManyListenersException;
import javax.comm.CommPortIdentifier;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.SerialPortEvent;
import javax.comm.SerialPortEventListener;
import javax.comm.UnsupportedCommOperationException;
import javax.xml.bind.DatatypeConverter;




public class COMConnect_DLMS
{ 
   public static InputStream inputStream;
   public static OutputStream outputStream;  
   SerialPort serialPort;  
   public long baudRate=19200;
   public int dataBits=SerialPort.DATABITS_8;
   public int stopBits=SerialPort.STOPBITS_1;
   public int parity=SerialPort.PARITY_NONE;
   boolean portFound = false;  
   String defaultPort="COM1";  
   static Enumeration portList ;     
   public static  CommPortIdentifier portId;

   public  COMConnect_DLMS()
  {
   initialize();
  }

private void initialize()
{
    System.out.println("Establishing connection to UART");
    portList = CommPortIdentifier.getPortIdentifiers();  
    while (portList.hasMoreElements()) 
    {  
        portId = (CommPortIdentifier) portList.nextElement();  
        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
        {  
            if (portId.getName().equals(defaultPort)) 
            {  
                System.out.println("Found port: "+defaultPort);  
                portFound = true; 
            }
        }
    }
     try 
    {  
     serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);  
    } 
    catch (PortInUseException e) {} 
    System.out.println(portId.getName());

     try
    {
        inputStream=serialPort.getInputStream();
    }
    catch (IOException e) {e.printStackTrace();}
    /*try
    {
        serialPort.addEventListener((SerialPortEventListener) this);
    }
    catch(TooManyListenersException e){}
    serialPort.notifyOnDataAvailable(true);*/
    try 
    {  
     // set port parameters  
     serialPort.setSerialPortParams((int) baudRate, dataBits,stopBits,parity);  
    }
    catch (UnsupportedCommOperationException e) {}


    try
    {
        outputStream=serialPort.getOutputStream();
    }
    catch (IOException e) {}
}


 public void serialEvent(SerialPortEvent event)
 {

    if(event.getEventType()==SerialPortEvent.DATA_AVAILABLE)
    {
        byte[] readBuffer = new byte[20];

        try 
        {
            while (inputStream.available() > 0)
            {
                int numBytes = inputStream.read(readBuffer);
            }
            System.out.print(new String(readBuffer));
        } 
        catch (IOException e) {System.out.println(e);}

    }
}
public static void writePacket(byte[] msg)
{
   System.out.println("Writing \""+DatatypeConverter.printHexBinary(messageString));  
  try 
  {  
    // write string to serial port  
     outputStream.write(msg);  
    //  System.out.println("written");
  } 
  catch (IOException e) {}

}

}

如果是串口,我还想了解更多关于NullPointerException的信息。谢谢。您的建议将不胜感激。

1 个答案:

答案 0 :(得分:2)

嗯,这是一个问题:

try {
    serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
} catch (PortInUseException e) {
}

如果由于某种原因,您无法打开该特定端口,则会出现空catch块。更糟糕的是,您没有报告发生了什么,或者为什么决定连接失败。

但这就是打破你的原因。您忽略了serialPort变量发生的任何错误,并将其设置为null。它以字段的形式初始化。

如果您未能通过通话获得实例,那么您就不应该继续。考虑一下:

  • System.exit(1)区块中发出catch来电,表明您的计划无法继续,或
  • (更好的选择)在与serialPort try...catch中的{{1}}有关的初始化方法中包装 所有内容
相关问题