`
ljl_xyf
  • 浏览: 617875 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics