java執行cmd命令和linux命令

來源:互聯網
上載者:User


一:window下執行cmd指定

程式例子:

/*該方法實現檔案自動複製功能。利用系統命令將指定檔案名稱從源路徑複製到目的路徑     * 如果目的路徑不存在時,自動建立目的路徑     * */ 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命令

程式例子:

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);    } }
執行結果:



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.