有些时候会碰到这样的场景: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. BLE CC2541 串口BootLoader 即 SBL BootLoader 资料 收集

    1.[CC254X_Bootloader]SBL(串口Bootloader)使用说明 2.CC2540协议栈高速串口通信解决(UART的DMA方式) 3.[BLE]CC2541之SBL 4.[BLE] ...

  2. font-failmly字体对应

  3. Python入门语法

    Python入门语法 动态变量 a=3  整数 a='abc'   a="abc"    字符串 a=3.0       小数 a=true  a=false   布尔型 a=3  ...

  4. PlanetLab介绍

    转自http://blog.sina.com.cn/s/blog_83517c050100vyzq.html PlanetLab产生背景 随着计算机技术和通信技术的不断发展,Internet的商业化和 ...

  5. DB数据源之SpringBoot+Mybatis踏坑过程实录系列(一)

    DB数据源之SpringBoot+MyBatis踏坑过程(一) liuyuhang原创,未经允许进制转载 系列目录 DB数据源之SpringBoot+Mybatis踏坑过程实录(一) DB数据源之Sp ...

  6. jquery file upload使用

    <!-- jquery file upload相关js --> <script src="/js/jquery-file-upload/js/jquery.ui.widge ...

  7. 【memcached的常用操作】

    memcache是一个KEY-VALUE存储缓存数据库,常用作网站数据请求的存储; 提供多种API: 语法简单类似于redis; #设置一个键值存储 #添加一个键值存储 #获取键值 #删除键值 #清空 ...

  8. jQuery 实现下载进度条

    //ajax异步上传 $.ajax({ url: "${pageContext.request.contextPath }/upload", type: "POST&qu ...

  9. Flink-on-yarn

    介绍 官网下载 https://www.apache.org/dyn/closer.lua/flink/flink-1.6.1/flink-1.6.1-bin-hadoop28-scala_2.11. ...

  10. C语言顺序队列

    顺序队列是一种只能在一头进和另一头出的数据结构,所以结构体里设2个指针分别指向头部和尾部,用数组来存储数据. #define MAXSIZE 1024 typedef int elemtype; ty ...