我有一个允许用户按下按钮的程序,然后它运行一个命令行语句,用户可以看到输出。
我现在想知道是否可以在命令完成之前停止命令。 在正常运行命令提示符时我知道命令“ctrl + c”,但是,我不确定如何在java程序中实现它。
runButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent r) {
JFrame runFrame = new JFrame("Running process...");
runFrame.setSize(500, 400);
runFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
runFrame.setLayout(null);
JButton somethingButton = new JButton("Stop");
JButton closeButton = new JButton("Close");
somethingButton.setBounds(65, 290, 105, 25);
closeButton.setBounds(335, 290, 105, 25);
JTextArea run = new JTextArea();
JScrollPane runSP = new JScrollPane(run);
runSP.setBounds(65, 50, 375, 200);
run.setLineWrap(true);
run.setWrapStyleWord(true);
run.setEditable(false);
runFrame.add(runSP);
runFrame.add(somethingButton);
runFrame.add(closeButton);
runFrame.setVisible(true);
//Start of creating of command line stuff
Runtime runtime = Runtime.getRuntime();
Process process = null;
try {
process = runtime.exec("ping riot.de");
} catch (IOException e1) {
System.err.print("Error: " + e1);
e1.printStackTrace();
}
try {
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
run.setText(sb.toString());
} catch (IOException e) {
System.err.println("Error: " + e);
}
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent c) {
runFrame.dispose();
}
});
somethingButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent c) {
//CODE TO STOP HERE
}
});
}
});
答案 0 :(得分:3)
尝试使用上述代码来解析流程process.destroy();