Java和C#運行命令行並獲取返回值 運行bat文件

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();
		}
	}

 

 

發佈了401 篇原創文章 · 獲贊 7 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章