irpas技术客

java中执行shell脚本_知识学徒_java执行shell脚本

大大的周 2207

文章目录 明确场景代码总结命令本身与参数一定要分离

明确场景 在项目中需要执行shell脚本或者shell命令。

具体而言:

需要通过一个文件夹路径,获取路径下所有git库路径。 而我本身已经有了这个shell脚本如下: #!/bin/bash path=${1} cd $path for git_path in `find . -name ".git" | awk -F . '{print $2}'` do dir=$path${git_path} dir=${dir%?} echo "${dir}" done 将这一脚本集成到java项目中。执行shell脚本获得终端输出的结果 代码 首先,仍旧是按照TDD的思想,写好测试。 @Test public void should_get_repo_list_from_dir_string() throws IOException { String addr = "/Users/code"; List<String> repoList = getRepoListByDir(addr); assertEquals("/Users/code", repoList.get(0)); //已知该项目下的第一个代码库路径 } private List<String> getRepoListByDir(String addr) throws IOException { String commandType = "sh"; String param1 = "src/main/java/cn/edu/fudan/projectmanager/shell/getRepoList.sh"; String param2 = addr; List<String> result = execAndReturn(commandType, param1, param2); return result; } 再编写代码通过测试: public static List<String> execAndReturn(String commandType, String param1, String param2) throws IOException { String[] commands = {commandType, param1, param2}; Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(commands); List<String> result = new ArrayList<>(); BufferedReader print = new BufferedReader(new InputStreamReader(proc.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream())); // Read the output from the command String s = null; while ((s = print.readLine()) != null) { result.add(s); } // Read any errors from the attempted command while ((s = stdError.readLine()) != null) { throw new RuntimeException("shell comand exec failed: " + s); } return result; } 总结 命令本身与参数一定要分离

在终端执行shell命令如下: sh src/main/java/cn/edu/fudan/projectmanager/shell/getRepoList.sh /Users/code

在java中使用执行过程中需要进行拆分成三个字符串:

“sh” “src/main/java/cn/edu/fudan/projectmanager/shell/getRepoList.sh” “/Users/code”

String[] commands = {commandType, param1, param2}; Process proc = Runtime.getRuntime().exec(commands);

对于不同参数个数的shell命令可以通过变长参数处理。

public static List<String> execAndReturn(String ... param) throws IOException { String[] commands = param; ... }


1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,会注明原创字样,如未注明都非原创,如有侵权请联系删除!;3.作者投稿可能会经我们编辑修改或补充;4.本站不提供任何储存功能只提供收集或者投稿人的网盘链接。

标签: #java执行shell脚本 #PATH1