I just got started with Linux development and recently encountered the problem of calling shell scripts in Java. I found a method suitable for cainiao-level development, as described below:
Add # In the first line of the shell script to be run #! /Bin/sh
Then run chmod A + X test. Sh on the terminal to convert test. Sh to an executable file.
Note that the directories run in Java may be different from those run by shell users. We recommend that you use full paths, such as/root/bin/test. Sh.
AllCode
Bytes ------------------------------------------------------------------------------------------------------------------------------
Import java. Io. ioexception;
Import java. Io. inputstreamreader;
Import java. Io. linenumberreader;
Public class runshell {
Public static void main (string [] ARGs ){
Try {
Process = runtime.getruntime(cmd.exe C ("/home/TINA/desktop/cal_time.sh ");
Inputstreamreader IR = new inputstreamreader (process. getinputstream ());
Linenumberreader input = new linenumberreader (IR );
String line;
While (line = input. Readline ())! = NULL)
System. Out. println (line );
Input. Close ();
IR. Close ();
} Catch (ioexception e ){
// Todo: handle exception
E. printstacktrace ();
}
}
}
Bytes -----------------------------------------------------------------------------------------------------------------------------
The script can be correctly executed. The code is running and the verification is correct.