Search code examples
javauser-interfacecmdswigprocessbuilder

How can I run windows command promt from java application?


At the moment I try to make application with GUI. This application have to run cmd with some commands. I am trying to do it. I want to realize action(When I push button "search"-command promt is openning). I tried to use ProcessBuilder to achieve the target but I dont have result. As you can see below, I try to run cmd with "dir" command. I tried do without running some commands, but CMD is steal not running. As result we don't see window and process in task manager. This is my code:

    package sys.tool;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//Создаем поля

public class MainWindow extends JFrame{
    private JLabel lcn = new JLabel("Enter computer name:");
    private JTextField icn = new JTextField("", 5);
    private JButton search = new JButton("Search");
    private JLabel lun = new JLabel("Enter user name:");
    private  JTextField iun = new JTextField("", 5);
    private JLabel empty = new JLabel("");


public MainWindow (){
    super("SysAdminTool");
    this.setBounds(100, 100, 700 , 90);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setResizable(false);

    Container container = this.getContentPane();
    container.setLayout(new GridLayout(3, 2 , 1, 1));
    container.add(lcn);
    container.add(icn);

    container.add(lun);
    container.add(iun);

    container.add(empty);
    search.addActionListener(new SearchEventListener());
    container.add(search); //this is button
}

class  SearchEventListener implements ActionListener{
    public void actionPerformed (ActionEvent e){
       ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "dir C:\\Users"); \\here I try to run cmd with command "dir"
    }
}


}

Solution

  • To run command on OS.

    String command = "command of the operating system";
    Process process = Runtime.getRuntime().exec(command);