实现获取命令行的返回结果

复制代码
 1 /**
 2  * @author liuwenlong
 3  * @create 2020-07-24 15:00:39
 4  */
 5 @SuppressWarnings("all")
 6 public class TestRunTime {
 7     public static String exeCmd(String commandStr) {
 8         BufferedReader br = null;
 9         try {
10             Process p = Runtime.getRuntime().exec(commandStr);
11             br = new BufferedReader(new InputStreamReader(p.getInputStream(),"gbk"));
12             String line = null;
13             StringBuilder sb = new StringBuilder();
14             while ((line = br.readLine()) != null) {
15                 sb.append(line + "\n");
16             }
17             return sb.toString();
18         } catch (Exception e) {
19             e.printStackTrace();
20         } finally {
21             if (br != null) {
22                 try {
23                     br.close();
24                 } catch (Exception e) {
25                     e.printStackTrace();
26                 }
27             }
28         }
29         return commandStr;
30     }
31 
32     public static void main(String[] args) {
33         String commandStr = "ping 127.0.0.1";
34         System.out.println(TestRunTime.exeCmd(commandStr));
35     }
36 }
复制代码

 

posted @   勤快的懒羊羊  阅读(368)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示