文章出處http://blog.csdn.net/xh16319/article/details/17302947
一:window下執行cmd指定
一:window下執行cmd指定 程序例子: [java] view plain copy /*該方法實現文件自動復制功能。利用系統命令將指定文件名從源路徑復制到目的路徑 * 如果目的路徑不存在時,自動創建目的路徑 * */ public static boolean copyFile(String origpath, String destpath, String filename) throws Exception{ String osName = System.getProperty("os.name"); boolean flag = false; /*系統命令支持的操作系統Windows XP, 2000 2003 7*/ if(!(osName.equalsIgnoreCase("windows XP") || osName.equalsIgnoreCase("windows 2000") || osName.equalsIgnoreCase("windows 2003") || osName.equalsIgnoreCase("windows 7"))){ return flag; } Runtime rt = Runtime.getRuntime(); Process p = null; File f = new File(destpath); if(!f.exists()){ f.mkdirs(); } int exitVal; p = rt.exec("cmd exe /c copy " + origpath+filename+" "+destpath); // 進程的出口值。根據慣例,0 表示正常終止。 exitVal = p.waitFor(); if(exitVal == 0){ flag = true; }else{ flag = false; } return flag; } public static void main(String[] args) { try { copyFile("D:\\DATA\\", "D:\\a\\", "131204.txt"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } 二:linux下執行shell命令 程序例子: [java] view plain copy package edu.test; import java.io.InputStreamReader; import java.io.LineNumberReader; /** * java在linux環境下執行linux命令,然后返回命令返回值。 * @author lee */ public class ExecLinuxCMD { public static Object exec(String cmd) { try { String[] cmdA = { "/bin/sh", "-c", cmd }; Process process = Runtime.getRuntime().exec(cmdA); LineNumberReader br = new LineNumberReader(new InputStreamReader( process.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = br.readLine()) != null) { System.out.println(line); sb.append(line).append("\n"); } return sb.toString(); } catch (Exception e) { e.printStackTrace(); } return null; } public static void main(String[] args) { // TODO Auto-generated method stub String pwdString = exec("pwd").toString(); String netsString = exec("netstat -nat|grep -i \"80\"|wc -l").toString(); System.out.println("==========獲得值============="); System.out.println(pwdString); System.out.println(netsString); } } 執行結果:
Java調用命令行並獲取執行結果
import java.io.BufferedReader; import java.io.InputStreamReader; public class Command { public static void exeCmd(String commandStr) { BufferedReader br = null; try { Process p = Runtime.getRuntime().exec(commandStr); br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = null; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line + "\n"); } System.out.println(sb.toString()); } catch (Exception e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (Exception e) { e.printStackTrace(); } } } } public static void main(String[] args) { String commandStr = "ping www.taobao.com"; //String commandStr = "ipconfig"; Command.exeCmd(commandStr); } }