linux java 调用 shell java 调用 linux .sh

原文转自:http://dreamthinking.blog.163.com/blog/static/205181171201235103945974/

java 调用 linux shell   java 调用 linux .sh

 

执行shell命令语法如下(显示指定目录下的文件,类似命令依次类推):

Runtime.getRuntime().exec(newString[]{"命令","参数1","参数2"});

其中: command参数第一个command[0]为linux命令,command[1].command[2]...其余项为参数  

(在网上找了很多例子,千篇一律,只是发布的作者不同罢了)
 
例:
/** 在/home/thinking//workplace 目录下创建myTest文件夹*/

Runtime.getRuntime().exec(newString[]{"mkdir","/home/thinking/workplace/myTest"});

 

/** 显示thinking 目录下的文件 */

Runtime.getRuntime().exec(newString[]{"ls","/home/thinking/"});

 

/** 创建文件 */

Runtime.getRuntime().exec(newString[]{"touch","/home/thinking//workplace/mytest"});

 

 
下面列举一个比较容易理解形式,调用shell脚本:

String[] commands =newString[]{"/home/thinking/helloWorld.sh","param1","param2"};

try{
Process process =Runtime.getRuntime().exec(command);
InputStream im = process.getInputStream();
BufferedReader br =newBufferedReader(newInputStreamReader(im));

String line ="";
while((line = br.readLine())!=null){
System.out.println(line);
}

}catch(IOException e){
e.printStackTrace();
}

上述命令运行了 /home/thinking目录下的 helloWorld.sh这个脚本,其中param1 和 param2为helloWorld的参数列表,此段代码将输出脚本中echo的信息。

 

猜你喜欢

转载自lxyd000.iteye.com/blog/1894193
今日推荐