有些时候会碰到这样的场景: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. pem文件转p12

    p12->pem cer.p12: openssl pkcs12 -clcerts -nokeys -out cer.pem -in cer.p12 key.p12: openssl pkcs1 ...

  2. 我的QT5学习之路(三)——模板库、工具类和控件(下)

    一.前言 作为第三篇的最后一部分,我们来看一下Qt的控件,谈到控件,就会让人想到界面的美观性和易操作性,进而想到开发的便捷性.作为windows界面开发的MFC曾经是盛行了多少年,但是其弊端也随着其他 ...

  3. winrar 弹窗处理

    https://www.rarlab.com/ 1.下载英文版 2.把下面这段code文本复制到一个新建的记事本txt文档中,然后另存为rarreg.key文件,注意后缀名.txt改为.key才行. ...

  4. javascript 获取排列后的对象建值

    function getSortedParameter (parameterObject){ let attributes = []; parameterObject = parameterObjec ...

  5. (Les16 执行数据库恢复)-表空间恢复

    NOARCHIVELOG模式下丢失了数据文件     数据库处于NOARCHIVELOG模式时,如果丢失任何数据文件,执行以下步骤         1.如果实例尚未关闭,请关闭实例         2 ...

  6. iOS:位置相关(18-03-09更)

    1.定位设置 2.定位页面逻辑 1.定位设置 2.定位页面逻辑 1).第一次进入该VC,在 viewDidLoad 调用刷新页面 refreshLocationView .这时用户还没决定,会刷出“正 ...

  7. javascript 中x++和++x的不同

    x++和++x都是给x加一,但是前者是完成赋值之后再递增x,后者相反. 例如:如果x是5,y=x++会将y设置为5,x设置为6:而y=++x会将x和y都设置为6.

  8. MySQL数据查询(重点)

    1.查询所有列   * 为所有列 select * from table_name; 2.查询指定列 select id,age from table_name; 3.查询时添加常量列-------本 ...

  9. Windows搭建SFTP服务器

    1.项目需要搭建一个SFTP服务器,网上搜了一下,用的是freeSSHd软件,网上查一下我用的是1.3.1版本https://freesshd.updatestar.com/网址自己下载即可. 2.安 ...

  10. 客户端与服务器交互中的Token

    Token:在计算机身份认证中是令牌(临时)的意思,类似于 MD5 加密之后的长字符串 特点:1.随机性,不可预测  2.具有有限期 3.唯一 作用:1.防止重复提交  2.防止CSRF(跨站请求伪造 ...