有些时候会碰到这样的场景:java的功能里面要嵌入一个功能点,这个功能是通过是shell脚本实现的。这种时候就需要Java对脚本调用的支持了。

测试环境

Ubuntu16.04 i3-6100,12GB

Hello World

来看一个基本的例子

    Process exec = Runtime.getRuntime().exec(new String[] { "uname" ,"-a"});
exec.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(exec.getInputStream()));
System.out.println(reader.readLine()); Linux jason-Inspiron-3650 4.4.0-121-generic #145-Ubuntu SMP Fri Apr 13 13:47:23 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

解读Process

java.lang.Process类提供了获取输入、输出、等待执行和销毁进程的方法。

Process类可通过ProcessBuilder.start() 和 Runtime.exec 创建实例,从Java1.5开始,ProcessBuilder.start()是更推荐的做法,但网上的教程更多推荐用Runtime.exec()方法。

Modifier and Type Method Description
abstract void destroy () Kills the subprocess.
abstract int exitValue () Returns the exit value for the subprocess.
abstract InputStream getErrorStream () Returns the input stream connected to the error output of the subprocess.
abstract InputStream getInputStream () Returns the input stream connected to the normal output of the subprocess.
abstract OutputStream getOutputStream () Returns the output stream connected to the normal input of the subprocess.
abstract int waitFor () Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated.

继承体系上面,Process的实现类是JDK内置的,linux版本的jdk中只带有一个实现类UnixProcess。

与脚本交互

Process不但可以执行进程,还可以获取进程的返回结果。

    private String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
int exitCode = p.waitFor();
System.out.println(exitCode);
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(output.toString());
return output.toString();
} PING www.a.shifen.com (111.13.100.91) 56(84) bytes of data.
64 bytes from localhost (111.13.100.91): icmp_seq=1 ttl=52 time=7.66 ms
64 bytes from localhost (111.13.100.91): icmp_seq=2 ttl=52 time=7.90 ms
64 bytes from localhost (111.13.100.91): icmp_seq=3 ttl=52 time=14.0 ms --- www.a.shifen.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2003ms
rtt min/avg/max/mdev = 7.668/9.861/14.013/2.937 ms

总结

Java 执行脚本的方式其实类似用直接在bash里面执行脚本,区别在于环境有些变动,执行的效果和bash基本一致。

本文发布于微信公众号:可乐小数据(xiaokele_data)。

Java如何调用shell脚本的的更多相关文章

  1. Java代码调用Shell脚本并传入参数实现DB2数据库表导出到文件

    本文通过Java代码调用Shell脚本并传入参数实现DB2数据库表导出到文件,代码如下: import java.io.File; import java.io.IOException; import ...

  2. 用java代码调用shell脚本执行sqoop将hive表中数据导出到mysql

    1:创建shell脚本 touch sqoop_options.sh chmod 777 sqoop_options.sh 编辑文件  特地将执行map的个数设置为变量  测试 可以java代码传参数 ...

  3. 利用jmeter发起java请求调用shell脚本

    1.创建maven项目 在pom文件中加入依赖:     2.在路径src/main/java下创建类,如类名shellclass                     3.      创建jmet ...

  4. Java 调用 shell 脚本详解

    这一年的项目中,有大量的场景需要Java 进程调用 Linux的bash shell 脚本实现相关功能. 从之前的项目中拷贝的相关模块和网上的例子来看,有个别的“陷阱”造成调用shell 脚本在某些特 ...

  5. java调用shell脚本小demo

    复制指定文件cpp.sh: [root@localhost soft]# vim cpp.sh#!/bin/bash name="$1"\cp /home/soft/test/${ ...

  6. 调用shell脚本,IP处理

    //调用shell脚本,IP处理 package com.letv.sdns.web.utils; import org.slf4j.Logger; import org.slf4j.LoggerFa ...

  7. JAVA远程执行Shell脚本类

    1.java远程执行shell脚本类 package com.test.common.utility; import java.io.IOException; import java.io.Input ...

  8. Android应用程序如何调用shell脚本(一)

    转自: Android应用程序如何调用shell脚本(一) 一般来说, Android 下的应用程序可以“直接”得到的最大的权限为 system ,但是如果我们需要在程序中执行某些需要 root 权限 ...

  9. Spring Boot 实现看门狗功能 (调用 Shell 脚本)

    需要实现看门狗功能,定时检测另外一个程序是否在运行,使用 crontab 仅可以实现检测程序是否正在运行,无法做到扩展,如:手动重启.程序升级(如果只需要实现自动升级功能可以使用 inotify)等功 ...

随机推荐

  1. jfinal多数据源ActiveRecordPlugin

    因为项目需要从多个数据库取数据,所以需要配置多个数据源 尝试了ActiveRecordPlugin和DruidPlugin的多数据源,但是因为DruidPlugin在本地一直报错一个很奇怪的语法错误, ...

  2. Mac下python3配置Sklearn

    服务器要有Python 环境 ,也要有Python运行的依赖包,Java与Python使用Process进程进行通讯. 安装homebrew /usr/bin/ruby -e "$(curl ...

  3. 关于DP

    关于DP 似乎摸到了门槛呢,学着学着Dijkstra突然有了感觉. 我们遍历的时候会遍历整张图的每个点每条边,然后与已知的对比大小,如果比现在方案好,就放入数组 那么,DP岂不是同样的思想? 在背包问 ...

  4. 用JavaScript获取URL参数的方法之一

    若地址栏URL为:abc.html?m=tomms&c=allsearchlist&pageNo=1&pageNum=20&text=1 <script> ...

  5. CentOS7.6离线安装JDK1.8

    卸载CentOS自带的openJDK: 查看openJDK命令:rpm -qa|grep java 结果: java-1.8.0-openjdk-headless-1.8.0.181-7.b13.el ...

  6. JavaScript中的this详解(彻底弄懂js中的this用法)!

    要想学好js,那么其中那些特别令人混淆迷惑的知识点,就一定要弄清楚.this关键字就是其中让初学者比较迷惑的知识点之一,不过灵活运用this可以提升代码的性能和复用性,那么今天我就和大家一起来了解th ...

  7. Redis 持久化深入--机制、可靠性及比较

    本文是对 antirez 博客中 Redis persistence demystified 的翻译和总结.主要从Redis的持久化机制,提供何种程度的可靠性以及与其他数据库的比较三个方面进行讨论. ...

  8. jdbc之Statement和Preparement

    Jdbc DML 操作 Statement:静态SQL操作 每次操作都会将sql语句提交到数据库执行一次,性能比较低 // 1.加载驱动程序 Class.forName(driverName); // ...

  9. python3网络爬虫系统学习:第一讲 基本库urllib

    在python3中爬虫常用基本库为urllib以及requests 本文主要描述urllib的相关内容 urllib包含四个模块:requests——模拟发送请求 error——异常处理模块 pars ...

  10. python range,xrange区别

    range: 直接生成一个列表对象 xrange: 生成一个xrange对象 xrange使用: 操作一个非常大的数据时,而且没存比较吃紧的时,可以使用xrange来节省内存 xrange一般在循环里 ...