Principle:Javaof theruntime.getruntime (). EXEC (CommandText)can invoke executioncmdinstructions.
cmd/c diris the end of executiondircommand to close the command window.
cmd/k diris the end of executiondirCommand does not close the command window.
cmd/c start dirwill open a new window and executedircommand, the original window will be closed.
cmd/k start dirwill open a new window and executedircommand, the original window will not be closed.
Note: Added aStart, a new window opens,can be usedcmd/?View help information.
Examples are as follows:
1, fromDDiskCopya copy of the document toEdisk.
public static void Main (string[] args) {
try {
String cmdstr = "cmd/c copy d:\\test.txt e:\\";
Runtime.getruntime (). exec (CMDSTR);
}catch (Exception e) {
E.printstacktrace ();
}
}
Note: hereDthe directory under the disk should be used\\, if you useD:/test.txtwill be understood as the same/ Cthe same command, and the file path cannot be found;File.getabsolutepath ();
2, delete a file(Note is a single file, not a folder). Here, with the topCopyto theeDisk ofTest.txtfile as an example.
public static void Main (string[] args) {
try {
String cmdstr = "cmd/c del e:\\test.txt";
Runtime.getruntime (). exec (CMDSTR);
}catch (Exception e) {
E.printstacktrace ();
}
}
3, Force Deletee:/testall folders and files under the folder
public static void Main (string[] args) {
try {
String cmdstr = "cmd/c rd/s/q e:\\test";
Runtime.getruntime (). exec (CMDSTR);
}catch (Exception e) {
E.printstacktrace ();
}
}
Note: This is mainly"rd/s/q"played a role, so that whateverTestThere are several layers of folders, the folder under the number of files, are all forcibly deleted.
Call the system command using the following line of code:
Process process = Runtime.getruntime (). EXEC ("cmd/c copy d:\\test.txt e:");
Wherein, the methodexecthe parameters are the specific system commands you want to invoke. BecauseCopyis not an executable by itselfEXEfiles, so you need to add them in front ofcmd/cto start a console application. And to run an executable program, such as executing myFunder the plateTomcatinstall the file and write the command as:String cmdstr = "F:\\apache-tomcat-6.0.20.exe";
Calling Batch Code:
public static void Main (string[] args) {
String Path = "D:\\public.bat";
Runtime run = Runtime.getruntime ();
try {
Process process = Run.exec ("cmd.exe/k start" + path);
//Print the call results to the console
InputStream in = Process.getinputstream ();
while (In.read ()! =-1) {
System.out.println (In.read ());
}
In.close ();
Process.waitfor ();
} catch (Exception e) {
E.printstacktrace ();
}
}
Java call cmd command