我在主目录test.sh
中有一个名为~
的shell脚本文件。我想用java执行shell文件。我使用以下代码:
Runtime runtime = Runtime.getRuntime();
Process process = null;
String cmd[] = {"/bin/bash","~/test.sh"};
String[] env = {"PATH=/bin:/usr/bin/"};
try
{
process = runtime.exec(cmd,env);
process.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line = reader.readLine();
stringBuilder.append(line);
System.out.println("The token is " + stringBuilder.toString() );
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
当我尝试执行以下程序时,我得到null
,结果如下:
The token is null
我犯了错误?
test.sh
只有
echo "Hello"
答案 0 :(得分:1)
您需要在进程处于活动状态时从流中读取。在waitFor()返回后访问getInputStream是没有意义的,因为那时进程已经死了。你应该开始一个线程来读取getInputStream()。
类似的东西:
process = runtime.exec(cmd,env);
final BufferedReader reader = new BufferedReader(new InputStreamReader (process.getInputStream()));
final StringBuilder stringBuilder = new StringBuilder();
new Thread () {
public void run () {
String line = reader.readLine();
stringBuilder.append(line);
}
}.start ();
process.waitFor();