【Java】Java运行cmd命令直接导出.sql文件
- Java中的Runtime.getRuntime().exec(commandStr)可以调用执行cmd命令
1 package Util; 2 3 import java.io.File; 4 import java.text.SimpleDateFormat; 5 import java.util.Date; 6 7 8 public class ExportSqlUtil { 9 public static void main(String[] args) { 10 try { 11 backup("root","950906","station"); 12 } catch (Exception e) { 13 // TODO Auto-generated catch block 14 e.printStackTrace(); 15 } 16 } 17 public static boolean backup(String username,String password,String database){ 18 boolean bool = false; 19 String sqlFilename = database+"_" + new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date()) + ".sql"; 20 String cmd = "mysqldump -u "+username+" -p"+password+" --opt "+database+" > d:/"+sqlFilename; 21 22 try { 23 Process p = Runtime.getRuntime().exec("cmd /C" + cmd); 24 p.waitFor(); 25 bool = true; 26 } catch (Exception e) { 27 // TODO Auto-generated catch block 28 e.printStackTrace(); 29 } 30 return bool; 31 } 32 }
- 其中Process新建进程p,表示当前线程等待process这个线程执行完毕后,继续向下执行。
梦想要一步步来!