首页 > 代码库 > 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命令
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。