Java和C#運行命令列的例子對比

來源:互聯網
上載者:User

呵呵,剛給客戶解決了在C#裡運行命令列的例子,順便整理了一下Java的例子,大家參考對比一下

 

Java的

import java.io.BufferedReader;<br />import java.io.InputStream;<br />import java.io.InputStreamReader;<br />/**<br /> * Java運行命令列的例子<br /> *<br /> * @author JAVA世紀網(java2000.net)<br /> */<br />public class TestProcess {<br /> public static void main(String[] args) {<br /> try {<br /> // 如果需要啟動cmd視窗,使用<br /> // cmd /k start ping 127.0.0.1 -t<br /> Process p = Runtime.getRuntime().exec("ping 127.0.0.1 -t");<br /> InputStream is = p.getInputStream();<br /> BufferedReader reader = new BufferedReader(new InputStreamReader(is));<br /> String line;<br /> while ((line = reader.readLine()) != null) {<br /> System.out.println(line);<br /> }<br /> p.waitFor();<br /> is.close();<br /> reader.close();<br /> p.destroy();<br /> } catch (Exception ex) {<br /> ex.printStackTrace();<br /> }<br /> }<br />}

 

 

C# 的

using System;<br />using System.Collections.Generic;<br />using System.Text;<br />using System.Diagnostics;<br />using System.IO;<br />/**<br /> * C# 運行命令列的例子<br /> *<br /> * @author JAVA世紀網(java2000.net)<br /> */<br />namespace ConsoleApplication1<br />{<br /> class TestProcess<br /> {<br /> public static void executeCommand()<br /> {<br /> ProcessStartInfo start = new ProcessStartInfo("Ping.exe");//設定啟動並執行命令列檔案問ping.exe檔案,這個檔案系統會自己找到<br /> //如果是其它exe檔案,則有可能需要指定詳細路徑,如運行winRar.exe<br /> start.Arguments = "127.0.0.1 -t";//設定命令參數<br /> start.CreateNoWindow = true;//不顯示dos命令列視窗<br /> start.RedirectStandardOutput = true;//<br /> start.RedirectStandardInput = true;//<br /> start.UseShellExecute = false;//是否指定作業系統外殼進程啟動程式<br /> Process p = Process.Start(start);<br /> StreamReader reader = p.StandardOutput;//截取輸出資料流<br /> string line = reader.ReadLine();//每次讀取一行<br /> while (!reader.EndOfStream)<br /> {<br /> Console.Out.WriteLine(line);<br /> line = reader.ReadLine();<br /> }<br /> p.WaitForExit();//等待程式執行完退出進程<br /> p.Close();//關閉進程<br /> reader.Close();//關閉流<br /> }<br /> }<br />}<br />

 

運行結果相同,大家自己看吧

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.