How can cmd be used as a part of java program without starting it separately?

RajeeRim :

I want to create a java program which can take input input from user and pass that input to cmd and get and display output to user. I have seen many examples in internet but they only tell how to start cmd externally. But I don't want to start cmd. I want to use cmd as a part of my program such that it would not open up but only work just like performing some operation invisibly on the input and return the output. Can anyone tell?

Also I have tried little to search similar question in this site but didn't found. Sorry if it is a duplicate.

Lennart Behr :

You can use Runtime#exec for that. The following snippet shows how you can read the output of a certain command executed in cmd.exe.

public static String executeCommand(String command) throws IOException
{
    StringBuilder outputBuilder = new StringBuilder();
    Process process = Runtime.getRuntime().exec(new String[] {"cmd", "/c", command});
    BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String read = null;
    while((read = outputReader.readLine()) != null)
    {
        outputBuilder.append(read).append("\n");
    }
    outputReader.close();
    process.destroy();
    return outputBuilder.toString();
}

The following example shows how to communicate with a process interactively.

public static void main(String[] args) throws Exception {
    Process process = Runtime.getRuntime().exec(new String[]{"cmd", "/c", "cmd" /* Replace with the name of the executable */});
    Scanner scanner = new Scanner(System.in);
    PrintWriter printWriter = new PrintWriter(process.getOutputStream());
    BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    new Thread(() -> {
        try {
            String read = null;
            while ((read = outputReader.readLine()) != null) {
                System.out.println("Process -> " + read);
            }
            System.out.println("Finished executing.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }).start();
    while (scanner.hasNext()) {
        String cmd = scanner.nextLine();
        System.out.println(cmd + " -> Process");
        printWriter.write(cmd + "\n");
        printWriter.flush();
    }
    scanner.close();
    printWriter.close();
    outputReader.close();
    process.destroy();
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=195252&siteId=1