Java calls external commands

xiaoxiao2021-03-06  14

Public class execcommond {

Public execcommond () {}

/ **

* Execute a command

* @Param EXECSTR STRING Command String

* @Return String information when the command is incorrect.

* /

Public Static String Exec (String Excstr) {

Runtime runtime = runtime.getruntime (); get the current runtime object

String outinfo = ""; // Perform error output information

Try {

String [] args = new string [] {"sh", "-c", execStr}; // execute the command under Linux

/ / Execute the command under Windows

// String [] args = new string [] {"cmd", "-c", execStr};

Process proc = runtime.exec (args); // Start another process to execute commands

InputStream IN = proc.geterrorStream (); // Get error message output.

BUFFEREDReader Br = New BufferedReader (IN);

String line = "";

While (LINE = Br.Readline ())

! = null) {

Outinfo = Outinfo line "/ n";

System.out.println (Outinfo);

}

// Check if the command failed.

Try {

IF (Proc.WaitFor ()! = 0) {

System.err.Println ("exit value ="

Proc.exitvalue ());

}

}

Catch (InterruptedException E) {

System.err.Print (e);

E.PrintStackTrace ();

}

}

Catch (IOException E) {

Flag = false;

System.out.println ("Exec Error:" E.getMessage ());

E.PrintStackTrace ();

}

Finally {

Return Outinfo;

}

}

}

转载请注明原文地址:https://www.9cbs.com/read-49728.html

New Post(0)