Java和C#运行命令行的例子对比

本文对比了C#和Java实现运行命令行的例子,包括如何在Java中使用命令行API,以及C#中使用Process类来执行外部命令,并展示了各自的运行结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

呵呵,刚给客户解决了在C#里运行命令行的例子,顺便整理了一下Java的例子,大家参考对比一下

 

Java的

[java]  view plain copy
  1. import java.io.BufferedReader;  
  2. import java.io.InputStream;  
  3. import java.io.InputStreamReader;  
  4. /** 
  5.  * Java运行命令行的例子 
  6.  *  
  7.  * @author JAVA世纪网(java2000.net) 
  8.  */  
  9. public class TestProcess {  
  10.   public static void main(String[] args) {  
  11.     try {  
  12.       // 如果需要启动cmd窗口,使用   
  13.       // cmd /k start ping 127.0.0.1 -t  
  14.       Process p = Runtime.getRuntime().exec("ping 127.0.0.1 -t");       
  15.       InputStream is = p.getInputStream();  
  16.       BufferedReader reader = new BufferedReader(new InputStreamReader(is));  
  17.       String line;  
  18.       while ((line = reader.readLine()) != null) {  
  19.         System.out.println(line);  
  20.       }  
  21.       p.waitFor();  
  22.       is.close();  
  23.       reader.close();  
  24.       p.destroy();  
  25.     } catch (Exception ex) {  
  26.       ex.printStackTrace();  
  27.     }  
  28.   }  
  29. }  

 

 

C# 的

[c-sharp]  view plain copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. using System.Diagnostics;  
  5. using System.IO;  
  6. /** 
  7.  * C# 运行命令行的例子 
  8.  *  
  9.  * @author JAVA世纪网(java2000.net) 
  10.  */  
  11. namespace ConsoleApplication1  
  12. {  
  13.     class TestProcess  
  14.     {  
  15.         public static void executeCommand()  
  16.         {  
  17.             ProcessStartInfo start = new ProcessStartInfo("Ping.exe");//设置运行的命令行文件问ping.exe文件,这个文件系统会自己找到  
  18.             //如果是其它exe文件,则有可能需要指定详细路径,如运行winRar.exe  
  19.             start.Arguments = "127.0.0.1 -t";//设置命令参数  
  20.             start.CreateNoWindow = true;//不显示dos命令行窗口  
  21.             start.RedirectStandardOutput = true;//  
  22.             start.RedirectStandardInput = true;//  
  23.             start.UseShellExecute = false;//是否指定操作系统外壳进程启动程序  
  24.             Process p = Process.Start(start);  
  25.             StreamReader reader = p.StandardOutput;//截取输出流  
  26.             string line = reader.ReadLine();//每次读取一行  
  27.             while (!reader.EndOfStream)  
  28.             {  
  29.                 Console.Out.WriteLine(line);  
  30.                 line = reader.ReadLine();  
  31.             }  
  32.             p.WaitForExit();//等待程序执行完退出进程  
  33.             p.Close();//关闭进程  
  34.             reader.Close();//关闭流  
  35.         }  
  36.     }  
  37. }  

 

运行结果相同,大家自己看吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值