Java和C#运行命令行的例子对比,
分享于 点击 33528 次 点评:273
Java和C#运行命令行的例子对比,
Java的
[java] view plaincopyprint?- 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# 的
[c-sharp] view plaincopyprint?- 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();//关闭流
- }
- }
- }
运行结果相同,大家自己看吧
相关文章
- 暂无相关文章
用户点评