java执行shell/cmd命令

时间:2022-09-03 16:52:17
try {
Process p
=Runtime.getRuntime().exec("chmod 777 /home/bomb/MoveToy/WebRoot/a.sh " );
p.waitFor();

Process pro
= Runtime.getRuntime().exec(" /home/bomb/MoveToy/WebRoot/./a.sh " + num);
pro.waitFor();
System.out.println(
"run");
java.io.InputStream out
= pro.getInputStream();
int i;
String a
= "";
String b
= "";
int n=0;
ArrayList
<String> tmp = new ArrayList<String>() ;
while ((i = out.read()) != -1) {
char c=(char)i;
if(i==10)
{
//System.out.println(a);
tmp.add(a);
a
="";
continue;
}
if(i!=13&&i!=10)
{
//System.out.println(n++ +" : "+c+" "+i);
a += c;
}
}

int len=tmp.size();
//提取耗散值
String [] tmphaosan=new String [len];
for(i=0;i<len;i++)
{
tmphaosan[i]
=tmp.get(i).split(" ")[1];
//System.out.println(tmp.get(i).split(" ")[1].split("\\n")[0]);
}
String ans
="";
String anss
="";
for(i=1;i<len;i++)
{
ans
="";
String t1
=tmp.get(i-1).split(" ")[0];
String t2
=tmp.get(i).split(" ")[0];
for(int j=0;j<t1.length();j++)
{
//确保空格在后
if(t2.charAt(j)=='E')
{
//System.out.println(j+1+" "+t1.charAt(j)+" "+t2.charAt(j));
ans=(j+1)+","+ans;
}
if(t1.charAt(j)=='E')
{
ans
+=(j+1);
ans
+=",";
}
}
ans
+=tmphaosan[i];
ans
+=';';
anss
+=ans;
}
//System.out.println(anss);
PrintWriter pw = response.getWriter();
pw.write(anss);
}
catch (Exception e) {
System.out.println(num);
e.printStackTrace();
}

通过runtime类生成一个子进程,等待子线程执行完成。并且通过截获标准输出流来读取外部程序的输出内容。