Runtime.getruntime.exec注意事项

1.普通使用–简单命令

Runtime.getruntime.exec(command);

		    // 可以是命令本身(ls)或者是脚本(/usr/local/test.sh)
            String command = "ls";
            Process proc = Runtime.getRuntime().exec(command);
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line = null;
            //读取结果
             while((line = in.readLine()) != null) {
                 result.append(line);
             }
           
            in.close();
         

2.指定文件下执行命令

在 usr/local 文件下执行command命令。

Runtime.getRuntime().exec(command,new String[]{},"/usr/local")

注意事情(有过滤脚本)

如果命令中有管道|.此时执行命令是没有返回值的。必须采用编写脚本的方式。
获取java进程
eg: ps -ef|grep java

//这样是没有返回值的
Runtime.getRuntime().exec("ps -ef|grep java")
// 必须先写文件,然后执行文件脚本有返回值
File file = new File("/usr/local/grepCommand.sh")
if(!file.exists()){
  file.createNewFile();
}
 FileOutputStream fos = new FileOutputStream(file);
 fos.write("ps -ef|grep java".getBytes());
 fos.close();
 Runtime.getRuntime().exec("chmod 777 /usr/local/grepCommand.sh")
 //防止下面命令执行太快 权限还没好
 Thread.sleep(500);
 //此处可拿到结果
 Runtime.getRuntime().exec("/usr/local/grepCommand.sh")

注意事项2

如果执行的脚本是反复回写的流。执行的时候线程可能偶先自动中断的场景。

原因是网络不稳定,切换到光口中去。

相关推荐

  1. 数组 注意事项

    2024-05-02 23:26:02       49 阅读
  2. 换房注意事项

    2024-05-02 23:26:02       71 阅读
  3. RWMutex 注意事项

    2024-05-02 23:26:02       59 阅读
  4. Unity 开发注意事项

    2024-05-02 23:26:02       47 阅读
  5. 国产系统注意事项

    2024-05-02 23:26:02       25 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-02 23:26:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-02 23:26:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-05-02 23:26:02       87 阅读
  4. Python语言-面向对象

    2024-05-02 23:26:02       96 阅读

热门阅读

  1. 2024最新华为OD机试试题库全 -【找单词】- C卷

    2024-05-02 23:26:02       32 阅读
  2. Xcode安装与配置

    2024-05-02 23:26:02       26 阅读
  3. RedisTemplate实现令牌桶限流

    2024-05-02 23:26:02       23 阅读
  4. 网络新闻的力量:如何用网络爬虫挖掘数据宝藏

    2024-05-02 23:26:02       36 阅读
  5. linux 创建管理员用户并使用生成秘钥登录服务器

    2024-05-02 23:26:02       32 阅读
  6. MySQL:DDL和DML语句

    2024-05-02 23:26:02       34 阅读
  7. 「笔试刷题」:添加逗号

    2024-05-02 23:26:02       28 阅读
  8. 基于python的天气网站数据爬取和可视化分析项目

    2024-05-02 23:26:02       32 阅读
  9. UIViewController中添加一个局部的 UITableView

    2024-05-02 23:26:02       26 阅读
  10. 机器人技术概述_2.机器人4.0的核心技术

    2024-05-02 23:26:02       30 阅读
  11. 【Python】Python基础

    2024-05-02 23:26:02       25 阅读
  12. vue加载vuetify模板UI

    2024-05-02 23:26:02       34 阅读