package test; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; /** * Java调用Windows命令测试 * @author liuyazhuang * */ public class Test { public static void main(String args[]) { testWinCmd(); dirOpt(); } public static void testWinCmd() { System.out.println("------------------testWinCmd()--------------------"); Runtime runtime = Runtime.getRuntime(); System.out.println(runtime.totalMemory()); System.out.println(runtime.freeMemory()); System.out.println(runtime.maxMemory()); System.out.println(runtime.availableProcessors()); //处理器数 try { //执行一个exe文件 runtime.exec("notepad"); runtime.exec("C:\\Program Files\\Microsoft Office\\OFFICE11\\winword.exe c:\\test.doc"); //执行批处理 runtime.exec("c:\\x.bat"); //执行系统命令 runtime.exec("cmd /c dir "); runtime.exec("cmd /c dir c:\\"); // //-------------- 文件操作 -------------- runtime.exec("cmd /c copy c:\\x.bat d:\\x.txt"); //copy并改名 runtime.exec("cmd /c rename d:\\x.txt x.txt.bak"); //重命名 runtime.exec("cmd /c move d:\\x.txt.bak c:\\"); //移动 runtime.exec("cmd /c del c:\\x.txt.bak"); //删除 //-------------- 目录操作 -------------- runtime.exec("cmd /c md c:\\_test"); //删除 } catch (IOException e) { e.printStackTrace(); } } /** * 执行批处理文件,并获取输出流重新输出到控制台 */ public static void dirOpt() { System.out.println("------------------dirOpt()--------------------"); Process process; try { //执行命令 process = Runtime.getRuntime().exec("c:\\x.bat"); //取得命令结果的输出流 InputStream fis = process.getInputStream(); //用一个读输出流类去读 BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String line = null; //逐行读取输出到控制台 while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } }
del c:\del.txt cd D: dir
------------------testWinCmd()-------------------- 2031616 1652120 66650112 2 ------------------dirOpt()-------------------- D:\_dev_stu\fileopt>del c:\del.txt D:\_dev_stu\fileopt>cd D: D:\_dev_stu\fileopt D:\_dev_stu\fileopt>dir 驱动器 D 中的卷是 DISK1_VOL2 卷的序列号是 70FB-DFAF D:\_dev_stu\fileopt 的目录 2008-07-18 09:30 <DIR> . 2008-07-18 09:30 <DIR> .. 2008-07-18 09:30 <DIR> src 2008-07-18 09:31 549 fileopt.iml 2008-07-18 09:31 10,292 fileopt.ipr 2008-07-18 14:27 <DIR> classes 2008-07-18 16:42 26,265 fileopt.iws 3 个文件 37,106 字节 4 个目录 8,095,498,240 可用字节 Process finished with exit code 0
原文地址:http://blog.csdn.net/l1028386804/article/details/44180583