java中调用cmd命令被阻塞无法返回和继续执行

  • Post author:
  • Post category:java

在项目中用到了数据库的备份和恢复功能,就通过java的Runtime.getRuntime().exec()来调用cmd或者linux命令来导出和导入.sql文件。但是在执行恢复时,程序一直被阻塞,没法往下运行,很头疼。代码有点糙:

        public static void main(String[] args) {
               String filepath="D:/Program_Files/Tomcat8.0/webapps/examine/ProductImg/backup.sql";
//             System.out.println("导入数据库结果:"+recover(filepath));
               constract(filepath);
        }
        public static int constract(String filepath){

        String ip=Mydbconnection.getHost();
        String database="examine";
//      String database=Mydbconnection.getDbname();
        String userName=Mydbconnection.getUsername();
        String password=Mydbconnection.getPassword();

        String stmt1 = "mysqladmin -h "+ip+" -u "+userName+" -p"+password+" create "+database;
        String stmt2 = "mysql -h"+ip+" -u"+userName+" -p"+password+" "+database+" < \"" + filepath+"\"";
        String cmd = "cmd /k "+stmt2;
        System.out.println(stmt1);
        System.out.println(cmd);
        exect(stmt1);
        exect(cmd);
               return 0;
        }
        public static int exect(String comm){
               int finished=0;
               try {
                       Runtime rt=Runtime.getRuntime();
                       Process proc=rt.exec(comm);
                       InputStream stderr=proc.getErrorStream();
                       InputStreamReader isr=new InputStreamReader(stderr);
                       BufferedReader br=new BufferedReader(isr);
                       String line=null;
                       System.out.println("<error></error>");
                       while((line=br.readLine())!=null){
//                             String encoded=new String(line.getBytes("gbk"),"GB18030");//GB2312/CP936/GB18030
//                             System.out.println(encoded);
                               System.out.println(line);
                       }
                       System.out.println();
                       int exitVal=proc.waitFor();
                       System.out.println("Process exitValue:"+exitVal);
                       finished=exitVal;
               } catch (Exception e) {
                       e.printStackTrace();
               }
               return finished;
        }

 

刚开始一直显示一串乱码,整了好半天,虽然没整好,但是也猜到它想表示啥了——“系统找不到指定的路径”,原来是文件的路径有问题,真的是坑。

真正的问题出在第二条去exec()执行的cmd字符串中,cmd后面跟的参数为/k,百度了一下,发现/k表示执行完毕不关闭窗口,/c是执行完毕关闭窗口。换成/c就好了。


版权声明:本文为mylf19原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。