First, write an linux shell script, that used to print 101 number -- 1-100 . words after # are comments
i=0 #declare a variable and set it to 0
while [$i -le 100] #to judge if i less equal 100
do # loop
echo $i # print the value of i
let i = $i + 1 # and implemented by other two ways: a.i=$(($i+1)) b.i='expr $i + 1'
done
Then we can write an application to execute above script
package edu.hnu.second;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class AnotherImpl {
public static void main(String[] args) {
try {
String[] cmd = { "/bin/bash",
"/home/develop/workspace/ShellTest/display0to100" }; // this path is the location where above
// script located
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = br.readLine();
while(line !=null)
{
System.out.println(line);
line = br.readLine();
}
br.close();
p.getErrorStream().close();
p.getOutputStream().close();
int retVal = p.waitFor();
System.out.println("wait " + retVal);
} catch (Exception e) {
e.printStackTrace();
}
}
}
i=0 #declare a variable and set it to 0
while [$i -le 100] #to judge if i less equal 100
do # loop
echo $i # print the value of i
let i = $i + 1 # and implemented by other two ways: a.i=$(($i+1)) b.i='expr $i + 1'
done
Then we can write an application to execute above script
package edu.hnu.second;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class AnotherImpl {
public static void main(String[] args) {
try {
String[] cmd = { "/bin/bash",
"/home/develop/workspace/ShellTest/display0to100" }; // this path is the location where above
// script located
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = br.readLine();
while(line !=null)
{
System.out.println(line);
line = br.readLine();
}
br.close();
p.getErrorStream().close();
p.getOutputStream().close();
int retVal = p.waitFor();
System.out.println("wait " + retVal);
} catch (Exception e) {
e.printStackTrace();
}
}
}
本文介绍了一个简单的 Linux Shell 脚本,该脚本用于打印从0到100的所有整数,并通过一个 Java 应用程序调用此脚本来展示如何在 Java 中执行 Shell 命令。

239

被折叠的 条评论
为什么被折叠?



