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();
}
}
}
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。