有些时候会碰到这样的场景: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. linux mysql access denied for user ‘root’@’localhost'(using password:YES)

    linux安装完mysql后,使用程序连接报以上错误解决方法,重新设置密码,步骤如下 1.先停掉原来的服务 service mysqld stop 2.使用安全模式登陆,跳过密码验证 mysqld_s ...

  2. 深入理解Java虚拟机(一) 运行时数据区划分

    前言:从我学Java的第一天开始,我的大学老师就告诉我 Java语言相比C.C++的语言有一个非常强大的功能,那就是自动内存管理:我们用Java编码时不需要申请或释放内存等,这些工作全部交由我们的Ja ...

  3. iOS TabBarItem设置红点(未读消息)

    实现原理: 其实是自定义一个view,将view添加到UITabBar上面,也可以是一个按钮,设置背景图片,和label.废话少说直接上代码搞一个UITabBar的分类 #import <UIK ...

  4. thinkPHP写txt日志文件

     file_put_contents(DATA_PATH.'文件名.txt', '收到请求:' . date('Y-m-d H:i:s') . PHP_EOL . '通知信息:' . $显示的变量名. ...

  5. VB错误说明

    1001 800A03E9 内存不足 1002 800A03EA 语法错误 1003 800A03EB 缺少“:” 1005 800A03ED 需要 '(' 1006 800A03EE 需要 ')' ...

  6. 树莓派3B+学习笔记:8、安装MySQL

    1.打开终端,先执行: sudo apt-get update 2.再执行: sudo apt-get install mysql-server 输入“y”确认并回车 3.初始化MySQL,输入: s ...

  7. 树莓3B+_安装vim

    第一步:访问源列表里的每个网址,并读取软件列表,然后保存在本地电脑. sudo apt-get update 第二步:安装vim sudo apt-get install vim 第三步:配置vim ...

  8. python 文件读取方法详解

    话不多说直接码 # 绝对路径 # f = open('/Users/fangxiang/Downloads/我的古诗.text', mode='r', encoding='utf-8') # cont ...

  9. Python安装tesserocr遇到的各种问题及解决办法

    Tesseract的安装及配置 在Python爬虫过程中,难免遇到各种各样的验证码问题,最简单的就是​这种验证码了,那么在遇到验证码的时候该怎么办呢?我们就需要OCR技术了,OCR-即Optical ...

  10. SSM-CRUD入门项目——查询

    查询 1.基础查询 分析:访问项目主页 index.jsp 时应该跳转到列表页 我们可以在index.jsp发出查询员工列表请求,来到 list.jsp 使用插件 pageHelper 完成分页功能— ...