Java calls Linux commands

Source: Internet
Author: User
Java calls Linux commands-general Linux technology-Linux programming and kernel information. The following is a detailed description. Java can directly call Linux commands in the following format: runtime.getruntime(cmd.exe c (command)

For example, run the ls and top command: runtime.getruntime(cmd.exe c ("ls ");

However, there is no output during this execution. cause: the runtime.exe c method will generate a local Process and return an instance of the Process subclass. (Note: runtime.getruntime(cmd.exe c (command) returns an instance of the Process class ). This instance can be used to control processes or obtain information about processes. since the sub-Process created by calling the runtime.exe c method does not have its own terminal or console, the standard IO (such as stdin, stdou, stderr) of the sub-Process passes the Process. getOutputStream (), Process. getInputStream (), Process. the getErrorStream () method is redirected to its parent process. you need to use these streams to input data to the sub-process or obtain the output of the sub-process. you can use the following methods:

Try
{
Process process = runtime.getruntime(cmd.exe c ("ls ");

InputStreamReader ir = newInputStreamReader (process. getInputStream ());
LineNumberReader input = new LineNumberReader (ir );

String line;
While (line = input. readLine ())! = Null ){
System. out. println (line)
}
Catch (java. io. IOException e ){
System. err. println ("IOException" + e. getMessage ());
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.