I have a program that allows a user to press a button, and then it runs a command line statement that the user is able to see the output of.
I now want to know if it's possible to stop the command before it finishes. I know of the command "ctrl+c" when running command prompt normally, however, I'm not sure how you would implement this in a java program.
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 } }); } });
Process::destroyForcibly?