首页 > 代码库 > Java实现操作dos命令

Java实现操作dos命令

java实现操作dos命令的两种方式

1.读取文件中的命令

package com;
import java.io.InputStream;
public class cmd {
	        public static void main(String[] args) {
	        String path = "D:\\cmd.bat";
	        Runtime run = Runtime.getRuntime();
	        try {
	            //run.exec("cmd /k shutdown -s -t 3600");
	            Process process = run.exec("cmd.exe /k start " + path);
	            InputStream in = process.getInputStream();
	            while (in.read() != -1) {
	                System.out.println(in.read());
	            }
	            in.close();
	            process.waitFor();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
    }
	
}

技术分享 

运行结果如下:

技术分享

 

第二种方式,直接读取命令

package com;
import java.io.BufferedReader;  
import java.io.InputStreamReader;   
public class qumf {    
    public static void main(String[] args) {  
      try {  
              Runtime rt = Runtime.getRuntime();  
              Process pr = rt.exec("cmd /c ping www.baidu.com && dir");
              //Process pr = rt.exec("D:\\xunlei\\project.aspx");    
              BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream(), "GBK"));  
              String line = null;  
              while ((line = input.readLine()) != null) {  
                  System.out.println(line);  
              }  
              int exitVal = pr.waitFor();  
              System.out.println("Exited with error code " + exitVal);  
  
           } catch (Exception e) {  
             System.out.println(e.toString());  
             e.printStackTrace();  
        }  
    }  
}  

技术分享

 

Java实现操作dos命令