java 实现操作dos命令

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

1.读取文件中的命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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();  
        }  
    }  
}  
复制代码

 

作者:Agoly
出处:https://www.cnblogs.com/qmfsun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
如果文中有什么错误,欢迎指出。以免更多的人被误导。
posted @ 2021-02-23 12:06  瓜子花生小板凳  Views(196)  Comments(0Edit  收藏  举报