Transferred from: http://blog.csdn.net/tengdazhang770960436/article/details/12014839
1.shell file return.sh
Echo 1
Echo 2
Echo 3
2.java file Test.java
[Java]View PlainCopy
- Import Java.io.BufferedInputStream;
- Import Java.io.BufferedReader;
- Import Java.io.InputStreamReader;
- Public class Test {
- public static void Main (string[] args) throws Exception {
- //define parameters for incoming shell script, put parameters into string array
- String cmds[] = new string[9];
- cmds[0] = "/home/aiuap_cj/report/return.sh";
- cmds[1] = "1"; //Task province ID
- cmds[2] = "2"; Insert the identity of the tax principal to which the task person belongs
- cmds[3] = "3"; Task duration
- cmds[4] = "4"; Statistics list Type (1: Calculation table, 2: Declaration form)
- cmds[5] = "5"; Insert the task person's level two company ID
- cmds[6] = "6"; Table name
- cmds[7] = "7";
- cmds[8] = "8"; Library name
- //Execute shell script
- Process pcs = Runtime.getruntime (). exec (CMDS);
- //define shell return values
- String result = null;
- //Get Shell return stream
- Bufferedinputstream in = new Bufferedinputstream (Pcs.getinputstream ());
- //character stream to convert byte streams
- BufferedReader br = new BufferedReader (new InputStreamReader (in));
- //The text log can also be output here
- String Linestr;
- While ((Linestr = Br.readline ()) = null) {
- result = Linestr;
- }
- //Close input stream
- Br.close ();
- In.close ();
- System.out.println ("==============================" + result);
- }
- }
Explain:
The value that the shell returns to Java is done through ECHO, and the shell return value that Java obtains is the last echo value, so the value that Java above can get is 3.
If you want to record errors in the execution of a script, you can change the return.sh as follows:
Echo 1
Echo 2
Echo 3
Rm-r/8888.txt 2>error.log
One of the problems here is that you cannot return the error message from the command execution to the Java caller directly, you can return the command execution result to the Java caller, then write the resulting error log to the development file, and then read the log file to see the error message.
Echo 1
Echo 2
Echo 3
Rm-r/8888.txt 2>error.log
echo $?
Java calls the shell to get the return value