您的位置:首页 > 运维架构 > Shell

Java调用shell脚本并获得结果

2015-04-24 16:39 417 查看
/**
* 运行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;
}

  
<span style="font-family: Arial, Helvetica, sans-serif;">`</span>
</pre><pre name="code" class="java">
/**
* cmd 脚本执行方法
* 该方法不执行任何逻辑.
* 就是判断操作系统,返回执行结果是否成功.
*
* @param invoke执行的shell脚本命令
*/
public static String cmdControler2(String invoke) {
System.out.println(invoke);
if (invoke == null)
return null;
// 获取操作系统的名称 如:"Windows 7" or "Linux"
String osName = System.getProperties().getProperty("os.name");
String[] cmd_arr = new String[] { "/bin/sh", "-c", invoke };
// // 根据操作系统生成shell脚本
if (osName.contains("Windows"))
cmd_arr = new String[] { "cmd", "/c", invoke };
Process process = null;
BufferedReader result = null, error = null;
try {
process = new ProcessBuilder(cmd_arr).start();
// 功能是一样的
// Process process = Runtime.getRuntime().exec(cmd_arr);
String str = "";
result = new BufferedReader(new InputStreamReader(
process.getInputStream()));
error = new BufferedReader(new InputStreamReader(
process.getErrorStream()));
while ((str = result.readLine()) != null) {
// 成功提示
// 此处的成功提示不需要显示
// System.out.println(str);
return str;
}
while ((str = error.readLine()) != null) {
// 存在错误提示
System.out.println(str);
return ERRORSTR + str;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
// 关闭流
if (result != null) {
try {
result.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (error != null) {
try {
error.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 释放process
if (process != null)
process.destroy();
}
// 前面的都没有执行就说明没有成功
return "";
}

  虽然使用Runtime.exec不是创建独立于平台的Java的最佳方式,但是有些时候是必要的。使用这种重定向技术有助于走出Runtime.exec的限制。 说明:
1.     exec的必须是可执行的程序,如果是命令行的命令则还需另外处理
2.     在windows中process
= runtime.exec(new String[] { "cmd.exe","/C", "dir"});
3.     在linux中process
= runtime.exec(new String[] { "/bin/sh","-c", "echo $PATH"});

            // 功能是一样的

            // Process process = Runtime.getRuntime().exec(cmd_arr);

              Process process = new ProcessBuilder(cmd_arr).start();

这两个是一样的效果。

上面的方法是我写的。直接改改就行。抽象成工具类就可以了。

复制去Google翻译翻译结果
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: