Java運行命令行的例子
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* Java運行命令行的例子
*
* @author JAVA世紀網(java2000.net)
*/
public class TestProcess {
public static void main(String[] args) {
try {
// 如果需要啓動cmd窗口,使用
// cmd /k start ping 127.0.0.1 -t
Process p = Runtime.getRuntime().exec("ping 127.0.0.1 -t");
InputStream is = p.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
p.waitFor();
is.close();
reader.close();
p.destroy();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
C# 運行命令行的例子
using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.IO; /** * C# 運行命令行的例子 * * @author JAVA世紀網(java2000.net) */ namespace ConsoleApplication1 { class TestProcess { public static void executeCommand() { ProcessStartInfo start = new ProcessStartInfo("Ping.exe");//設置運行的命令行文件問ping.exe文件,這個文件系統會自己找到 //如果是其它exe文件,則有可能需要指定詳細路徑,如運行winRar.exe start.Arguments = "127.0.0.1 -t";//設置命令參數 start.CreateNoWindow = true;//不顯示dos命令行窗口 start.RedirectStandardOutput = true;// start.RedirectStandardInput = true;// start.UseShellExecute = false;//是否指定操作系統外殼進程啓動程序 Process p = Process.Start(start); StreamReader reader = p.StandardOutput;//截取輸出流 string line = reader.ReadLine();//每次讀取一行 while (!reader.EndOfStream) { Console.Out.WriteLine(line); line = reader.ReadLine(); } p.WaitForExit();//等待程序執行完退出進程 p.Close();//關閉進程 reader.Close();//關閉流 } } }
BAT文件
public static void main(String[] args) { try { String path=System.getProperty("user.dir"); // 如果需要啓動cmd窗口,使用 // cmd/kstartping127.0.0.1-t Process p = Runtime.getRuntime().exec(path+"\\callODI.bat"); InputStream is = p.getInputStream(); BufferedReader reader = new BufferedReader( new InputStreamReader(is)); String line = ""; while ((line = reader.readLine()) != null) { System.out.println(line); } p.waitFor(); is.close(); reader.close(); p.destroy(); } catch (Exception ex) { ex.printStackTrace(); } }