我正在开发一个COM端口应用程序,我需要为从COM端口接收到Java控制台的数据设置一个Timer函数。 我的代码是
public void Print_data_function() {
try{
serialPort = (SerialPort)portId.open("SimpleReadApp",10000);
}
catch(PortInUseException ae)
{
System.out.println(ae+" port in use beta");
}
timer.schedule(new Serial_Port_Operation(), 2000,1000); /* Application breaks up here when debugging is done*/
System.out.println("Application Started");
try{
inputStream = serialPort.getInputStream();
} catch(IOException dd)
{
System.out.println("IOE exception");
}
}
class Serial_Port_Operation extends TimerTask
{
@Override
public void run()
{
boolean data_recieved = false;
byte[] readBuffer = new byte[1];
try {
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
data = data + new String(readBuffer);
data_recieved = true;
}if(data_recieved == false)
{
if ( data.length() > 0)
{
print_data();
}
}
} catch (IOException e) {System.out.println(e);}
}
控制台上显示的错误是
COM2
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at serial_printer.Serial_Printer.Print_data_function(Serial_Printer.java:202)
at serial_printer.Serial_Printer.com_portsActionPerformed(Serial_Printer.java:137)
at serial_printer.Serial_Printer.access$000(Serial_Printer.java:21)
at serial_printer.Serial_Printer$1.actionPerformed(Serial_Printer.java:87)
如何成功访问Timer函数中的类。