【问题标题】:Read and Write from serial port in java without listener event在没有监听器事件的情况下从java中的串口读取和写入
【发布时间】:2015-02-13 04:22:26
【问题描述】:

我想从串口读取字节并按顺序写入。有什么方法可以通过在 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 的信息。谢谢。您的建议将不胜感激。

【问题讨论】:

  • 那么...在哪里这个NullPointerException发生在哪里?
  • 它出现在语句中:inputStream=serialPort.getInputStream();
  • 那很可能是您的 serialPort 变量必须为空
  • @ThusithaThilinaDayaratne :我能知道为什么它是空的吗?我在上面的代码中做错了什么?
  • 可能是因为serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);抛出异常仍然 serialPort 为空

标签: java nullpointerexception inputstream


【解决方案1】:

嗯,这有点问题:

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

如果由于某种原因您无法打开该特定端口,则您有一个空的 catch 块。更糟糕的是,您没有报告发生的事情,或者它决定连接失败的原因。

但这就是让你崩溃的原因。您忽略serialPort 变量发生的任何错误,并将其设置为null。它以这种方式初始化为一个字段。

如果您未能从调用中获取实例,则不应继续。考虑:

  • 在您的 catch 块中调用 System.exit(1) 以指示您的程序无法继续,或者
  • (更好的选择)将 everything 包裹在与 serialPort 相关的初始化方法中,并放入您的 try...catch

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-28
    • 2014-10-25
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 2018-08-04
    • 2021-10-26
    相关资源
    最近更新 更多