How to write into and read from command line in Java ? [duplicate]

为君一笑 提交于 2019-12-02 07:13:30

问题


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();


来源:https://stackoverflow.com/questions/7433073/how-to-write-into-and-read-from-command-line-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!