用java跑程序, 入门应用

      JAVA世界 2004-7-14 19:8
import java.io.*;

public class runcmd
{
public static void main(String[] args)
throws Exception
{
if (args.length > 0) {

__runcmd(args[0]);
return;
}

String[] cmd = {"bash", "-c", "echo 123 >> /tmp/abc"};
//String[] cmd = {"bash", "/tmp/test.sh"};
//String[] cmd = {"bash", "-c", "/tmp/test.sh"};

__runcmd(cmd);
return;
}

private static void __runcmd(String cmd)
throws Exception
{
Process ps = Runtime.getRuntime().exec(cmd);
System.out.println(_stringStream(ps.getInputStream()));

int ret = ps.waitFor();
System.out.println("run command {" + cmd + "} complete.");
if (0 != ret)
{
String st = "mission Failed " + ret + " !";
System.out.println(st);
throw new Exception(st);
}
System.out.println("mission Accomplish!");

return;
}

private static void __runcmd(String cmd[])
throws Exception
{
Process ps = Runtime.getRuntime().exec(cmd);
System.out.println(_stringStream(ps.getInputStream()));

int ret = ps.waitFor();
String s = "run command: {";
for (int i = 0; i < cmd.length; i++)
{
s += cmd[i];
if ( (cmd.length - 1) != i ) s += " ";
}
s += "} complete.";
System.out.println(s);
if (0 != ret)
{
String st = "mission Failed " + ret + " !";
System.out.println(st);
throw new Exception(st);
}
System.out.println("mission Accomplish!");

return;
}

//...read InputStream to String
private static String _stringStream(InputStream in)
throws Exception
{
int ptr = 0;
in = new BufferedInputStream(in);
StringBuffer buffer = new StringBuffer();
while ( (ptr = in.read()) != -1 ) buffer.append((char)ptr);
return buffer.toString();
}
}
标签集:TAGS:
回复Comments() 点击Count()

回复Comments

{commentauthor}
{commentauthor}
{commenttime}
{commentnum}
{commentcontent}
作者:
{commentrecontent}
}