2

My problem is, after opening cmd from java code, i want user to be able to input like in c++ ms dos applications. When user writes sth such as "dir" or "cd..", i want to execute these codes by java. The problem is for every command java re-opens cmd again. Also i cannot execute commands. My cmd start code is below ;

final ArrayList<String> commands = new ArrayList<>();                

    commands.add("cmd.exe");
    commands.add("/C");
    commands.add("start");
    ProcessBuilder pb = new ProcessBuilder(commands);
    Process process = pb.start();

1 Answer 1

1

Here's some cleaned up code from How to open the command prompt and insert commands using Java?

public static void main(String[] args) {
    try {
        String ss = null;
        Runtime obj = null;
        Process p = Runtime.getRuntime().exec("cmd.exe");


        //write a command to the output stream
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
        writer.write("dir");
        writer.flush();

        //Get the input and stderror
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));


        System.out.println("Here is the standard output of the command:\n");
        while ((ss = stdInput.readLine()) != null) {
            System.out.println(ss);
        }

        System.out.println("Here is the standard error of the command (if any):\n");
        while ((ss = stdError.readLine()) != null) {
            System.out.println(ss);
        }

    } catch (IOException e) {
        System.out.println("FROM CATCH" + e.toString());
    }

}

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. Though it does not open cmd window from netbeans. Probably when i export the project as jar, maybe it will open cmd?
Also it does not write outputs to netbeans log window for example when i try dir etc
Does it succeed on the call for cmd.exe?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.