怎样在java代码中调用执行shell脚本

Python016

怎样在java代码中调用执行shell脚本,第1张

**

* 运行shell脚本

* @param shell 需要运行的shell脚本

*/

public static void execShell(String shell){

try {

Runtime rt = Runtime.getRuntime()

rt.exec(shell)

} catch (Exception e) {

e.printStackTrace()

}

}

/**

* 运行shell

*

* @param shStr

*需要执行的shell

* @return

* @throws IOException

*/

public static List runShell(String shStr) throws Exception {

List<String>strList = new ArrayList()

Process process

process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c",shStr},null,null)

InputStreamReader ir = new InputStreamReader(process

.getInputStream())

LineNumberReader input = new LineNumberReader(ir)

String line

process.waitFor()

while ((line = input.readLine()) != null){

strList.add(line)

}

return strList

}

// 用法:Runtime.getRuntime().exec("命令")

String shpath="/test/test.sh" //程序路径

Process process =null

String command1 = “chmod 777 ” + shpath

try {

Runtime.getRuntime().exec(command1 ).waitFor()

} catch (IOException e1) {

e1.printStackTrace()

}catch (InterruptedException e) {

e.printStackTrace()

}

String var="201102" /参数

String command2 = “/<a href="https://www.baidu.com/s?wd=bin&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1YkuARkryDYnjfYn1T3rjnd0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6KdThsqpZwYTjCEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-TLwGUv3EPjRdrHfYrHc3n104PW0znWfd" target="_blank" class="baidu-highlight">bin</a>/sh ” + shpath + ” ” + var

Runtime.getRuntime().exec(command2).waitFor()