1

I want to write a Java code that would perform commands in Windows CMD.

I looked through the site and found out how to send and work with single request. For example create new Process and in execute ("cmd /c dir") then using input stream I can get the answer that is displayed.

How to open the process of cmd and let the user to enter cmd commands?

For example, I open application and it directly opens cmd process, then user can type "dir" and get the output.

After type "cd ../../" and after type "dir" again and get the output with new path containment.

If it can be performed then how to do it? Or in order to perform this need to open each time a new process and execute ("cmd /c some_reqests")?

1
  • Just use console to get input and then use the users input to start exec process. Commented Feb 18, 2017 at 18:31

2 Answers 2

1

Nice question, you can in fact call cmd as a new process and use standard input and standard output to process data.

The tricky part is knowing when the stream from a command has ended.

To do so I used a string echoed right after the command (dir && echo _end_).

In practice I think it would be better to simply start a process for each task.

public class RunCMD {

    public static void main(String[] args) {
        try {
            Process exec = Runtime.getRuntime().exec("cmd");
            OutputStream outputStream = exec.getOutputStream();
            InputStream inputStream = exec.getInputStream();
            PrintStream printStream = new PrintStream(outputStream);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
            printStream.println("chcp 65001");
            printStream.flush();
            printStream.println("dir && echo _end_");
            printStream.flush();


            for(String line=reader.readLine();line!=null;line=reader.readLine()){
                System.out.println(line);
                if(line.equals("_end_")){
                    break;
                }
            }

            printStream.println("exit");
            printStream.flush();

            for(String line=reader.readLine();line!=null;line=reader.readLine()){
                System.out.println(line);
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

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

Comments

0

try this

    Process p = Runtime.getRuntime().exec("ps -ef");

found it at http://alvinalexander.com/java/edu/pj/pj010016

1 Comment

Thank, hope this will help

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.