ArticleDirectory
- 2. 1. Disadvantages:
- 2. solution:
- . Problems with automatic exit
1. References
1. Ask a question about executing the. BAT file in Java under Win-> answer on the 6th floor
2. How can I automatically exit after calling cmd to run the BAT file-> answer on the 11 th floor
3. Java calls bat
In the previous blog, I wrote about MySQL database backup and recovery. This is mainly done by manually calling the BAT file.Program. This is the topic of this blog.
2. instance 1:
Import Java. Io. ioexception;
Public Class Invokebat4 {
Public Void Runbat (string batname ){
String cmd = "CMD/C start F: \ database_backup \ ngx_backup \" + batname + ". Bat "; // Pass
Try {
Process PS = runtime.getruntime(cmd.exe C (CMD );
PS. waitfor ();
} Catch (Ioexception IOE ){
IOE. printstacktrace ();
}
Catch (Interruptedexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
System. Out. println ("Child thread Donn ");
}
Public Static Void Main (string [] ARGs ){
Invokebat4 test1 = New Invokebat4 ();
Test1.runbat ("backup_ngx ");
System. Out. println ("main thread ");
}
}
2. 1. Disadvantages:
The cmd box is displayed and cannot be closed automatically.
2. solution:
Add
Exit
For example, the content of the original BAT file is as follows:
Mysqldump-Uroot-Proot--Database ngx_ad ngx_authority ngx_jbpm ngx_mes ngx_model> F: \ database_backup \ ngx_backup \ ngx_db. SQL
We modify it
Mysqldump-Uroot-Proot--Database ngx_ad ngx_authority ngx_jbpm ngx_mes ngx_model> F: \ database_backup \ ngx_backup \ ngx_db. SQL
Exit
. Problems with automatic exit
Even if you can exit automatically, the CMD command box will always pop up every time you call this bat.
3. Improve the instance and directly execute bat
Import Java. Io. ioexception;
Import Java. Io. inputstream;
Public Class Invokebat2 {
Public Void Runbat (string batname ){
Try {
Process PS = runtime.getruntime(cmd.exe C (batname );
Inputstream in = ps. getinputstream ();
Int C;
While (C = in. Read ())! =-1 ){
System. Out. Print (C ); // If you do not need to view the output, you can cancel this line.
}
In. Close ();
PS. waitfor ();
} Catch (Ioexception IOE ){
IOE. printstacktrace ();
} Catch (Interruptedexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
System. Out. println ("Child thread done ");
}
Public Static Void Main (string [] ARGs ){
Invokebat2 test1 = New Invokebat2 ();
String batname = "f :\\ database_backup \ ngx_backup \ backup_ngx.bat ";
Test1.runbat (batname );
System. Out. println ("main thread ");
}
}