Redirection issues when Java programs call Linux commands

Source: Internet
Author: User


Java can call Linux commands through runtime in the following format:
Runtime.getruntime(cmd.exe C (command)
In this way, there is no output during execution, because calling runtime.exe C program will initiate a program and return the process class. Then, runtime.getruntime(cmd.exe C (command) returns a process class instance, which can be used to control the process or obtain information about the process. The sub-process created by calling the runtime.exe C method does not have its own terminal or console. The stdin, stdou, and stderr of the sub-process are respectively created through the process. getinputstream (), process. getoutputstream (), process. the geterrorstream () method is redirected to its parent process.
If you need to input data to a sub-process or obtain the output of the sub-process, you need to use these streams.

The following code obtains the execution result of the Linux Command:

import java.io.BufferedReader;import java.io.InputStreamReader;public class Hello {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubString command ="/home/hello/extract_exper/extract_each.sh 1.txt ";try {Process ps = Runtime.getRuntime().exec(command);BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));StringBuffer sb = new StringBuffer();String line;while ((line = br.readLine()) != null) {sb.append(line).append("\n");}String result = sb.toString();System.out.println(result);} catch (Exception e) {e.printStackTrace();}}}

 

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.