---
title: "shell 跟java 相互调用和获取结果"
author: "gohands"
date: "2011-11-08T15:16:50Z"
tags: ["Java", "Linux", "shell"]
categories: ["操作系统"]
slug: "shell-java"
draft: false
lastmod: "2011-11-08T15:16:50Z"
id: 1243360
url: "https://gohands.iteye.com/blog/1243360"
---

被调用的shell

a.sh

```
#!/bin/bash
echo 111
exit 8
```

 java 代码

```
	public static void main(String[] args) throws IOException {
		Process p = Runtime.getRuntime().exec(command);
		InputStream is = p.getInputStream();
		int data;
		StringBuffer strBuffer = new StringBuffer();
		while ((data = is.read()) != -1) {
			strBuffer.append((char) data);
		}
		
		System.out.println("命令:\n" + command);
		System.out.println("结果:\n" + p.exitValue());
		System.out.println("log:\n" + strBuffer.toString());
		int ret = p.exitValue(); // 全路径
		System.exit(ret); // 直接返回shell执行的结果
	}
```

 调用java的shell

test.sh

```
#!/bin/bash
#调用java打包后的jar文件
java -jar test.jar
#显示执行结果
echo $?
```