我试图通过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();
}
}
答案 0 :(得分:8)
您的cmd
显然是null
因为您的构造函数代码错误。写
this.cmd = cmd;
textArea相同。
答案 1 :(得分:3)
你的构造函数不符合你的想法:
public SystemInfoToTextArea(JTextArea textArea, String cmd) {
textArea = textArea;
cmd = cmd;
}
这只是重新分配参数(到它们自己的值!),并且没有使用相同的名称设置字段。你想要做的就是在它们前面添加:
public SystemInfoToTextArea(JTextArea textArea, String cmd) {
this.textArea = textArea;
this.cmd = cmd;
}
一个体面的IDE会警告你这个错误。