Java invokes the CMD command and outputs display information:
Package com.anxin.cmd.test;
Import Java.io.BufferedReader;
Import Java.io.InputStreamReader;
public class Command {public
static void Main (string[] args) {
try {
Runtime RT = Runtime.getruntime ();
Process PR = rt.exec ("cmd/c dir"); CMD/C Calc
//Process PR = rt.exec ("d:\\xunlei\\project.aspx");
BufferedReader input = new BufferedReader (New InputStreamReader (Pr.getinputstream (), "GBK"));
String line = null;
while (line = Input.readline ())!= null) {
System.out.println (line);
int exitval = Pr.waitfor ();
System.out.println ("Exited with error code" + exitval);
} catch (Exception e) {
System.out.println (e.tostring ());
E.printstacktrace ();}}
Three ways to start the native application exe in Java:
The first way: the use of CMD method
/**
* Execute cmd command
*
@param command
* @throws ioexception
/public
static String Executecmd ( String command) throws IOException {
log.info ("Execute command:" + command);
Runtime Runtime = Runtime.getruntime ();
Process process = Runtime.exec ("cmd/c" + command);
BufferedReader br = new BufferedReader (New InputStreamReader (Process.getinputstream (), "UTF-8"));
String line = null;
StringBuilder build = new StringBuilder ();
while (line = Br.readline ())!= null) {
log.info (line);
Build.append (line);
return build.tostring ();
}
Executecmd (Start "Axadwebbrowser" "D:\AXAdsBrowser\AXAdWebBrowser.exe");
The second way: using Processbuilder to invoke the Cmd method
/** *
Start Application
*
* @param programname
* @return
* @throws ioexception/public
static void StartProgram (String programpath) throws IOException {
log.info ("Launch application:" + Programpath);
if (Stringutils.isnotblank (Programpath)) {
try {
String programname = programpath.substring ( Programpath.lastindexof ("/") + 1, Programpath.lastindexof ("."));
list<string> list = new arraylist<string> ();
List.add ("cmd.exe");
List.add ("/C");
List.add ("Start");
List.add ("\" "+ ProgramName +" "");
List.add ("\" "+ Programpath +" "");
Processbuilder Pbuilder = new Processbuilder (list);
Pbuilder.start ();
} catch (Exception e) {
e.printstacktrace ();
Log.error ("app:" + Programpath + "does not exist!) ");
}
}
}
The third way: Start the application with desktop
/** *
Start Application
*
* @param programname
* @return
* @throws ioexception/public
static void StartProgram (String programpath) throws IOException {
log.info ("Launch application:" + Programpath);
if (Stringutils.isnotblank (Programpath)) {
try {
desktop.getdesktop (). Open (New File (Programpath));
catch (Exception e) {
e.printstacktrace ();
Log.error ("app:" + Programpath + "does not exist!) ");
}
}