本文代码来自:枫轩缘 的博客: Java调用命令行并获取执行结果
我稍微做了点更改:主要是为了导出成jar工具包,以后直接调用:
package system.call.cmd; import java.io.BufferedReader; import java.io.InputStreamReader; public class Command { public static String exeCmd(String commandStr) { BufferedReader br = null; StringBuilder sb = new StringBuilder(); try { Process p = Runtime.getRuntime().exec(commandStr); br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = null; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } } catch (Exception e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (Exception e) { e.printStackTrace(); } } } return sb.toString(); } }
导出成jar包后即可在其他地方使用。导出jar工具包步骤:
(1)选择JARfile方式导出:
(2)选择导出的目录:
(3)在其他工程中的Build Path导入该jar工具包:
选择:Add External JARs..
找到刚才导出的目录,选中这个jar工具包:
选择打开,点击OK即可
测试:
import system.call.cmd.Command; public class TestCommand { public static void main(String[] args) { String commandStr="ipconfig"; System.out.println(Command.exeCmd(commandStr)); } }
运行结果:
cmd运行bat文件:bat文件可以直接运行,所以输入bat文件名就可以直接调用。
实例:
public static void main(String[] args) { String commandStr="C:\\Users\\Administrator\\Desktop\\使用火狐打开网页.bat"; System.out.println(Command.exeCmd(commandStr)); }
使用火狐打开网页bat:
start F:\Program" "Files" "(x86)\Mozilla" "Firefox\firefox.exe ^ https://blog.csdn.net/qq_21808961
运行结果:
eclipse控制台输出:
D:\dev\workspace\RunableTools>start F:\Program" "Files" "(x86)\Mozilla" "Firefox\firefox.exe https://blog.csdn.net/qq_21808961同时火狐浏览器打开了我的博客
最后给上可执行jar的连接: