Java 調用cmd.exe命令


原理: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());
        }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM