文章目录
- 明确场景
- 代码
- 总结
- 命令本身与参数一定要分离
明确场景
- 在项目中需要执行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;
...
}