简体   繁体   English

如何在Java中停止命令行进程

[英]How to stop command line process in Java

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. 我在正常运行命令提示符时知道命令“ 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
            }
        });
    }
});

尝试使用提到的代码来取消进程process.destroy(); ;。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM