我有一個程序,允許用戶按下按鈕,然後運行命令行語句,用戶可以看到輸出。如何在Java中停止命令行過程
我現在想知道在結束之前是否可以停止命令。 當我正常運行命令提示符時,我知道命令「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
}
});
}
});
System.exit(0);不適合你? – Stultuske
@Stultuske我不想關閉整個程序。這是一個小片段。 – Plumel
因此......您想「停止」應用程序,而不是「停止」應用程序?你的意思是打斷一個線程? – Stultuske