码迷,mamicode.com
首页 > 编程语言 > 详细

Java 调用cmd.exe命令

时间:2018-01-09 16:47:03      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:readline   打开   exit   des   .bat   runtime   post   inpu   ted   

原理:java的Runtime.getRuntime().exec(commandText)可以调用执行cmd指令。

cmd /c dir 是执行完dir命令后关闭命令窗口。 
cmd /k dir 是执行完dir命令后不关闭命令窗口。

cmd /c start dir 会打开一个新窗口后执行dir指令,原窗口会关闭。 
cmd /k start dir 会打开一个新窗口后执行dir指令,原窗口不会关闭。 
注:增加了start,就会打开新窗口,可以用cmd /?查看帮助信息。

         public static void runCMD(String path) throws Exception 
        { 
                Process p = Runtime.getRuntime().exec("cmd /c cmd.exe /c " + path+" exit"); 
                BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));   
                String readLine = br.readLine();   
                while (readLine != null) { 
                    readLine = br.readLine(); 
                    System.out.println(readLine); 
                } 
                if(br!=null){ 
                    br.close(); 
                } 
                p.destroy(); 
                p=null; 
        } 
        public static void runCMDShow(String path) throws Exception 
        { 
            Process p = Runtime.getRuntime().exec("cmd /c start cmd.exe /c " + path+" exit"); 
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));   
            String readLine = br.readLine();   
            while (readLine != null) { 
                readLine = br.readLine(); 
                System.out.println(readLine); 
            } 
            if(br!=null){ 
                br.close(); 
            } 
            p.destroy(); 
            p=null; 
        } 
        public static void main(String[] args) {   
            String path = "D:\\iimob\\tomcat2\\bin\\startup.bat";  
            System.out.println(new Date()); 
            try { 
                runCMDShow(path); 
            } catch (Exception e) { 
                // TODO Auto-generated catch block 
                e.printStackTrace(); 
            } 
            System.out.println(new Date()); 
        }

Java 调用cmd.exe命令

标签:readline   打开   exit   des   .bat   runtime   post   inpu   ted   

原文地址:https://www.cnblogs.com/qiumingcheng/p/8251401.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!