How to write into and read from command line in Ja

2020-04-21 05:38发布

问题:

This question already has answers here:
Closed 8 years ago.

Possible Duplicate:
Java external program

I am trying to wrtie a program to write a command on a command line,

for example;

ipconfig

and then get the response of the command so I want to both write command to a command line and get its response. I have searched about it on the net and saw that apache cli is used to do this in Java but actually I did not clearly get how it can be done. Can you please help me about my situation with a few line of codes or tutorials about both writing and reading commands please?

Thank you all very much

回答1:

You could start it as a Process and capture the InputStream of the process as described here:

Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("ipconfig"); // you might need the full path
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;

while ((line = br.readLine()) != null) {
    System.out.println(line);
}

Edit: I copied this code from above link, but the code seems wrong. Don't you need the output stream for this? Edit2: no.

getInputStream()

Gets the input stream of the subprocess. The stream obtains data piped from the standard output stream of the process represented by this Process object.

Nice naming convention...



回答2:

See Process and ProcessBuilder classes.

Specifically, you would create a Process. Process.getOutputStream() gives an InputStream, from which you read what the process's output. You also need to read Process.getErrorStream() for any errors that the process reports.



回答3:

Try this for inputting the user value.

java.util.Scanner input = new Scanner( System.in);

System.out.println("Please Enter your Name: ");             
    String empName = input.nextLine();