在java中使用串行端口时,如何避免空指针异常?

在java中使用串行端口时,如何避免空指针异常?,java,nullpointerexception,serial-port,Java,Nullpointerexception,Serial Port,所以,我正在制作一个程序,通过发送命令与传感器进行通信。但是,当我尝试单击GUI中的按钮时,会出现两个错误:nullpointer异常和portinuse异常,这会阻止按钮工作。我该如何解决这个问题 SimpleRead类: import java.awt.event.ActionListener; import java.io.*; import java.util.*; import javax.comm.*; import javax.swing.*; public class S

所以,我正在制作一个程序,通过发送命令与传感器进行通信。但是,当我尝试单击GUI中的按钮时,会出现两个错误:nullpointer异常和portinuse异常,这会阻止按钮工作。我该如何解决这个问题

SimpleRead类:

import java.awt.event.ActionListener;
import java.io.*;
import java.util.*; 
import javax.comm.*;
import javax.swing.*;



public class SimpleRead  {
    static Enumeration portList;
    static CommPortIdentifier portId;
    static  PrintStream os;
    static BufferedReader is;
    static java.util.Timer t = new java.util.Timer();
    static TimersTask tt = new TimersTask();

    public static void main(String[] args) {

        GUI GUI = new GUI();
        JFrame window = new JFrame("DI-100"); 
        window.setSize(700, 300); 
        window.setVisible(true); 
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.add(GUI);

        Enumeration portList = CommPortIdentifier.getPortIdentifiers();
        String wantedPortName;
        CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
            ArrayList<String> serialports = new ArrayList<String>();
            serialports.add(portId.getName());
            String[] ports = new String[serialports.size()];
            ports = serialports.toArray(ports); 
            GUI.jComboBox2 = new JComboBox(ports);
            GUI.jComboBox2.addActionListener(GUI.jComboBox2);
            wantedPortName = (String) GUI.jComboBox2.getSelectedItem();


            while (portList.hasMoreElements()) { 
                if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL &&
                  portId.getName().equals(wantedPortName)) {
                    CommPortIdentifier pid = portId;
                    SerialPort port = null;


                    try {
                        port = (SerialPort) portId.open("OpenPort", 1000);

                    } catch(PortInUseException e) {
                        System.err.println("Port already in use: " + e);
                    }   



                    try {
                        port.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
                    }
                    catch (UnsupportedCommOperationException e) {
                        System.out.println("you suck");
                    }



                    try {
                        os = new PrintStream(port.getOutputStream(), true, "ISO-8859-1");
                    }
                    catch (IOException e) {
                        System.err.println("Can't open input stream: write-only");
                    }



                    try {
                        is = new BufferedReader(new InputStreamReader(port.getInputStream()));
                    } catch (IOException e) {
                        System.err.println("Can't open input stream: write-only");
                    }



                    try{
                        os = new PrintStream(port.getOutputStream(), true);
                    } catch (IOException e){   
                    }
                }
                else {
                }
            }
        }
    }
}
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*; 
import javax.comm.*;
import javax.swing.*;

public class SimpleRead  {
    static Enumeration portList;
    static CommPortIdentifier portId;
    static PrintStream os;
    static BufferedReader is;
    static java.util.Timer t = new java.util.Timer();
    static TimersTask tt = new TimersTask();

    public static void main(String[] args) {

        GUI GUI = new GUI();
        JFrame window = new JFrame("DI-100"); 
        window.setSize(700, 300); 
        window.setVisible(true); 
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.add(GUI);

        Enumeration portList = CommPortIdentifier.getPortIdentifiers();
        String wantedPortName;
        CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
            ArrayList<String> serialports = new ArrayList<String>();
            serialports.add(portId.getName());
            String[] ports = new String[serialports.size()];
            ports = serialports.toArray(ports); 
            GUI.jComboBox2 = new JComboBox(ports);
            GUI.jComboBox2.addActionListener(GUI.jComboBox2);
            wantedPortName = (String) GUI.jComboBox2.getSelectedItem();


            while (portList.hasMoreElements()) { 
                if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL &&
                  portId.getName().equals(wantedPortName)) {
                    CommPortIdentifier pid = portId;
                    SerialPort port = null;


                    try {
                        port = (SerialPort) portId.open("OpenPort", 1000);
                        port.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
                        os = new PrintStream(port.getOutputStream(), true, "ISO-8859-1");
                        is = new BufferedReader(new InputStreamReader(port.getInputStream()));
                        os = new PrintStream(port.getOutputStream(), true); // you had this line in your original code.  Is this really necessary, since you have a similar line 2 lines before it?
                    } catch(PortInUseException e) {
                        System.err.println("Port already in use: " + e);
                    } catch (UnsupportedCommOperationException e) {
                        System.out.println("you suck");
                    } catch (IOException e) {
                        System.err.println("Can't open input or output stream");
                    }
                }
                else {
                }
            }
        }
        try {
            os.close();
        } catch (Exception ex) {
            //already closed
        }
        try {
            is.close();
        } catch (Exception ex) {
            //already closed
        }
        // close the port here
    }
}

好吧,我想这就是正在发生的事情。您正在尝试打开端口:
port=(SerialPort)portId.open(“OpenPort”,1000),无论什么原因都会失败。然后继续使用它:
port.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE),但此时为空,因此程序将爆炸

SimpleRead类:

import java.awt.event.ActionListener;
import java.io.*;
import java.util.*; 
import javax.comm.*;
import javax.swing.*;



public class SimpleRead  {
    static Enumeration portList;
    static CommPortIdentifier portId;
    static  PrintStream os;
    static BufferedReader is;
    static java.util.Timer t = new java.util.Timer();
    static TimersTask tt = new TimersTask();

    public static void main(String[] args) {

        GUI GUI = new GUI();
        JFrame window = new JFrame("DI-100"); 
        window.setSize(700, 300); 
        window.setVisible(true); 
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.add(GUI);

        Enumeration portList = CommPortIdentifier.getPortIdentifiers();
        String wantedPortName;
        CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
            ArrayList<String> serialports = new ArrayList<String>();
            serialports.add(portId.getName());
            String[] ports = new String[serialports.size()];
            ports = serialports.toArray(ports); 
            GUI.jComboBox2 = new JComboBox(ports);
            GUI.jComboBox2.addActionListener(GUI.jComboBox2);
            wantedPortName = (String) GUI.jComboBox2.getSelectedItem();


            while (portList.hasMoreElements()) { 
                if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL &&
                  portId.getName().equals(wantedPortName)) {
                    CommPortIdentifier pid = portId;
                    SerialPort port = null;


                    try {
                        port = (SerialPort) portId.open("OpenPort", 1000);

                    } catch(PortInUseException e) {
                        System.err.println("Port already in use: " + e);
                    }   



                    try {
                        port.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
                    }
                    catch (UnsupportedCommOperationException e) {
                        System.out.println("you suck");
                    }



                    try {
                        os = new PrintStream(port.getOutputStream(), true, "ISO-8859-1");
                    }
                    catch (IOException e) {
                        System.err.println("Can't open input stream: write-only");
                    }



                    try {
                        is = new BufferedReader(new InputStreamReader(port.getInputStream()));
                    } catch (IOException e) {
                        System.err.println("Can't open input stream: write-only");
                    }



                    try{
                        os = new PrintStream(port.getOutputStream(), true);
                    } catch (IOException e){   
                    }
                }
                else {
                }
            }
        }
    }
}
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*; 
import javax.comm.*;
import javax.swing.*;

public class SimpleRead  {
    static Enumeration portList;
    static CommPortIdentifier portId;
    static PrintStream os;
    static BufferedReader is;
    static java.util.Timer t = new java.util.Timer();
    static TimersTask tt = new TimersTask();

    public static void main(String[] args) {

        GUI GUI = new GUI();
        JFrame window = new JFrame("DI-100"); 
        window.setSize(700, 300); 
        window.setVisible(true); 
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.add(GUI);

        Enumeration portList = CommPortIdentifier.getPortIdentifiers();
        String wantedPortName;
        CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
            ArrayList<String> serialports = new ArrayList<String>();
            serialports.add(portId.getName());
            String[] ports = new String[serialports.size()];
            ports = serialports.toArray(ports); 
            GUI.jComboBox2 = new JComboBox(ports);
            GUI.jComboBox2.addActionListener(GUI.jComboBox2);
            wantedPortName = (String) GUI.jComboBox2.getSelectedItem();


            while (portList.hasMoreElements()) { 
                if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL &&
                  portId.getName().equals(wantedPortName)) {
                    CommPortIdentifier pid = portId;
                    SerialPort port = null;


                    try {
                        port = (SerialPort) portId.open("OpenPort", 1000);
                        port.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
                        os = new PrintStream(port.getOutputStream(), true, "ISO-8859-1");
                        is = new BufferedReader(new InputStreamReader(port.getInputStream()));
                        os = new PrintStream(port.getOutputStream(), true); // you had this line in your original code.  Is this really necessary, since you have a similar line 2 lines before it?
                    } catch(PortInUseException e) {
                        System.err.println("Port already in use: " + e);
                    } catch (UnsupportedCommOperationException e) {
                        System.out.println("you suck");
                    } catch (IOException e) {
                        System.err.println("Can't open input or output stream");
                    }
                }
                else {
                }
            }
        }
        try {
            os.close();
        } catch (Exception ex) {
            //already closed
        }
        try {
            is.close();
        } catch (Exception ex) {
            //already closed
        }
        // close the port here
    }
}
这解决了你的一个问题,还有很多你不知道的问题。try/catch的工作方式是,当某个代码失败时,块中的其余代码不会运行,因为它取决于失败的代码。相反,您的代码只需在失败时一个接一个地抛出异常即可

根本问题是
PortInUseException
,这是不言自明的。其他内容已在使用该端口。检查您的代码(这里和其他地方)以确保您没有尝试打开端口两次(例如,如果您多次单击按钮,可能会?),如果这不能解决问题,您的计算机上可能有另一个程序获取端口


“记住,孩子们,在处理完端口后,请始终关闭它们!”

引发异常的那一行?在此处发布堆栈跟踪,以便我们可以找到异常的来源。