0

我有托盘来获取系统信息Runtime.getRuntime().exec(cmd);

我收到以下错误:

java.lang.NullPointerException
    at java.lang.Runtime.exec(Runtime.java:422)
    at java.lang.Runtime.exec(Runtime.java:326)
    at mytest.SystemInfoToTextArea.doInBackground(SystemInfoToTextArea.java:31)
    at mytest.SystemInfoToTextArea.doInBackground(SystemInfoToTextArea.java:16)

欢迎任何建议

班级代码

public class SystemInfoToTextArea extends SwingWorker<String, Void> {
private JTextArea textArea;
private String cmd;

public SystemInfoToTextArea(JTextArea textArea, String cmd) {
    textArea = textArea;
    cmd = cmd;
}

@Override
protected String doInBackground() throws Exception {
    String outputMem = null;
    try {
        String lineMem;
        outputMem = "";
        Process procMem = Runtime.getRuntime().exec(cmd);
        BufferedReader input =
                new BufferedReader
                        (new InputStreamReader(procMem.getInputStream()));
        while ((lineMem = input.readLine()) != null) {
            outputMem = (lineMem + "\n");

        }

        input.close();
    } catch (Exception err) {
        err.printStackTrace();
    }
    return outputMem;
}

@Override
protected void done() {
    super.done();
    try {
        textArea.append(get());
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

}

public static void main(String... args){
    JFrame frame = new JFrame();
    frame.setSize(700,500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel = new JPanel();
    JTextArea textArea = new JTextArea("System info");

    panel.add(textArea);
    frame.setContentPane(panel);

    frame.setVisible(true);

    SystemInfoToTextArea systemInfoToTextArea = new SystemInfoToTextArea(textArea,"cmd /C dir");
     systemInfoToTextArea.execute();

}
}
4

2 回答 2

8

cmd显然是null因为你的构造函数代码是错误的。写

this.cmd = cmd;

与 textArea 相同。

于 2012-05-04T14:04:28.757 回答
3

You constructor doesn't do what you think:

public SystemInfoToTextArea(JTextArea textArea, String cmd) {
    textArea = textArea;
    cmd = cmd;
}

This just reassigns the parameters (to their own values!), and doesn't set the fields with the same names. What you want to do is prefix them with this:

public SystemInfoToTextArea(JTextArea textArea, String cmd) {
    this.textArea = textArea;
    this.cmd = cmd;
}

A decent IDE would warn you of this mistake.

于 2012-05-04T14:08:08.553 回答