Transferred from: Http://blog.163.com/[email protected]/blog/static/1406291232012575743301/
Java runtime.getruntime (). EXEC (CommandText) can invoke the Execute CMD command
cmd/c dir closes the command window after executing the dir command.
cmd/k dir does not close the command window after executing the dir command.
cmd/c start dir will open a new window and execute the dir instruction, the original window will be closed.
cmd/k start dir will open a new window and execute the dir instruction, the original window will not be closed.
Examples are as follows:
1. Copy a document from the D-Disk to the E-drive.
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: Here in the D-disk directory to use \ \, if using d:/test.txt will be understood as the same as/C command, and cannot find the file path, so here can use File.getabsolutepath ();
2. Delete a file (note that it is a single file, not a folder). Here is an example of the Test.txt file from the above copy to E disk.
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. Forcibly delete all folders and files under the E:/test 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: Here is the main "rd/s/q" play a role, so no matter how many layers of test in the folder, folders 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:");
Where the method exec parameter is the specific system command you want to invoke. Because copy itself is not an executable EXE file, you need to add cmd/c earlier to start a console application. And to run an executable program, such as executing my Tomcat installation file under the F disk, write the command as: String cmdstr = "F:\\apache-tomcat-6.0.20.exe";
Call 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.exe command