JAVA调用SHELL事例
以往一直都是crontab+shell调用java程序,最近需要反过来,使用java调用shell程序,实现定时管理,今天总结一下。
基础内容:
java的java.lang.Runtime类提供了exec静态方法,可以执行本地脚本
程序事例:
package study; import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date; public class JavaShellUtil {
// 基本路径
private static final String basePath = "/tmp/"; // 记录Shell执行状况的日志文件的位置(绝对路径)
private static final String executeShellLogFile = basePath + "executeShell.log"; public static int executeShell(String shellCommand) throws IOException {
int success = 0;
StringBuffer stringBuffer = new StringBuffer();
BufferedReader bufferedReader = null;
// 格式化日期时间,记录日志时使用
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS "); try {
stringBuffer.append(dateFormat.format(new Date())).append("准备执行Shell命令 ").append(shellCommand).append(" \r\n"); Process pid = null;
String[] cmd = { "/bin/sh", "-c", shellCommand };
// 执行Shell命令
pid = Runtime.getRuntime().exec(cmd);
if (pid != null) {
stringBuffer.append("进程号:").append(pid.toString()).append("\r\n");
// bufferedReader用于读取Shell的输出内容
bufferedReader = new BufferedReader(new InputStreamReader(pid.getInputStream()), 1024);
int return = pid.waitFor(); //返回值是执行的结果,如果不是0,就是错误
} else {
stringBuffer.append("没有pid\r\n");
}
stringBuffer.append(dateFormat.format(new Date())).append("Shell命令执行完毕\r\n执行结果为:\r\n");
String line = null;
// 读取Shell的输出内容,并添加到stringBuffer中
while (bufferedReader != null && (line = bufferedReader.readLine()) != null) {
stringBuffer.append(line).append("\r\n");
}
} catch (Exception ioe) {
stringBuffer.append("执行Shell命令时发生异常:\r\n").append(ioe.getMessage()).append("\r\n");
}
if (bufferedReader != null) {
OutputStreamWriter outputStreamWriter = null;
try {
bufferedReader.close();
// 将Shell的执行情况输出到日志文件中
OutputStream outputStream = new FileOutputStream(executeShellLogFile);
outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
outputStreamWriter.write(stringBuffer.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
outputStreamWriter.close();
}
success = 1;
} return success;
} public static void main(String args[]) {
try {
int i = JavaShellUtil.executeShell("ls /");
System.out.println(i);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println(e);
}
}
}
环境说明:
1、日志文件:/tmp/executeShell.log
2、将JavaShellUtil.java放置到study目录,然后执行:
- javac study/JavaShellUtil.java
- java study/JavaShellUtil
捕获异常
java希望捕获shell的异常,除了上面的return,还可以使用Process对象的exitValue()方法,例如:pid.exitValue()。
当然如果希望获取shell的异常输出,那么还需要优化一段代码:
if (pid != null) {
stringBuffer.append("进程号:").append(pid.toString()).append("\r\n");
// bufferedReader用于读取Shell的输出内容
bufferedReader = new BufferedReader(new InputStreamReader(pid.getInputStream()), 1024);
InputStreamReader stderr = new InputStreamReader(pid.getErrorStream());
success = pid.waitFor();
if (success!=0){
BufferedReader br = new BufferedReader(stderr);
while ( (line = br.readLine()) != null){
logger.error(String.format("[%s]:[%s]:[%s] execute shell error [%s]", this.getJobName(), this.getTaskName(), this.getTaskRecordId(), line));
return success;
}
}
JAVA调用SHELL事例的更多相关文章
- Java 调用 shell 脚本详解
这一年的项目中,有大量的场景需要Java 进程调用 Linux的bash shell 脚本实现相关功能. 从之前的项目中拷贝的相关模块和网上的例子来看,有个别的“陷阱”造成调用shell 脚本在某些特 ...
- [转载]JAVA调用Shell脚本
FROM:http://blog.csdn.net/jj12345jj198999/article/details/11891701 在实际项目中,JAVA有时候需要调用C写出来的东西,除了JNI以外 ...
- java基础/java调用shell命令和脚本
一.项目需求: 从某一机构获取证书,证书机构提供小工具,执行.sh脚本即可启动服务,本地调用该服务即可获取证书. 问题:linux服务器启动该服务,不能关闭.一旦关闭,服务即停止. 解决方案:java ...
- java调用shell脚本小demo
复制指定文件cpp.sh: [root@localhost soft]# vim cpp.sh#!/bin/bash name="$1"\cp /home/soft/test/${ ...
- java调用shell获取返回值
转自:http://blog.csdn.net/tengdazhang770960436/article/details/12014839 1.shell文件return.sh echo 1 echo ...
- java调用shell脚本,并获得结果集的例子
/** * 运行shell脚本 * @param shell 需要运行的shell脚本 */ public static void execShell(String shell){ try { Run ...
- Java 调用 Shell 命令
近日项目中有这样一个需求:系统中的外币资金调度完成以后,要将调度信息生成一个Txt文件,然后将这个Txt文件发送到另外一个系统(Kondor)中.生成文件自然使用OutputStreamWirter了 ...
- Hadoop概念学习系列之Java调用Shell命令和脚本,致力于hadoop/spark集群(三十六)
前言 说明的是,本博文,是在以下的博文基础上,立足于它们,致力于我的大数据领域! http://kongcodecenter.iteye.com/blog/1231177 http://blog.cs ...
- java 调用shell命令
原文:http://kongcodecenter.iteye.com/blog/1231177 Java通过SSH2协议执行远程Shell脚本(ganymed-ssh2-build210.jar) ...
随机推荐
- 架构:The Onion Architecture : part 3(洋葱架构:第三篇)(转载)
In my previous installments, I described what has become my approach to defining the architecture fo ...
- YAML 语言教程
编程免不了要写配置文件,怎么写配置也是一门学问. YAML 是专门用来写配置文件的语言,非常简洁和强大,远比 JSON 格式方便. 本文介绍 YAML 的语法,以 JS-YAML 的实现为例.你可以去 ...
- 破产姐妹第一季/全集2 Broke Girls迅雷下载
本季2 Broke Girls Season 1 (2011)看点:黑发泼辣的Max(凯特·戴琳斯 Kat Dennings 饰)在纽约布鲁克林区一家低档餐馆打工,餐馆同事包括小个子亚裔老板Han L ...
- ExtJS 4.2 教程-02:bootstrap.js 工作方式
转载自起飞网,原文地址:http://www.qeefee.com/extjs-course-2-bootstrap-js ExtJS 4.2 教程-01:Hello ExtJS ExtJS 4.2 ...
- [Web 前端] 前端频道之团队维护、聚合、订阅
cp from :https://blog.csdn.net/ivan820819/article/details/78885404 国内 腾讯 ISUX 腾讯全端 AlloyTeam 奇舞周刊 阿里 ...
- 离线环境下使用二进制方式安装配置Kubernetes集群
本文环境 Redhat Linux 7.3,操作系统采用的最小安装方式. Kubernetes的版本为 V1.10. Docker版本为18.03.1-ce. etcd 版本为 V3.3.8. 1. ...
- Google SRE 读书笔记 扒一扒SRE用的那些工具
写在前面 最近花了一点时间阅读了<SRE Goolge运维解密>这本书,对于书的内容大家可以看看豆瓣上的介绍.总体而言,这本书是首次比较系统的披露Google内部SRE运作的一些指导思想. ...
- JavaScript:Date 对象
ylbtech-JavaScript:Date 对象 1.返回顶部 Date 对象 Date 对象用于处理日期和时间. 创建 Date 对象的语法: var myDate=new Date() 注释: ...
- 在ASP.NET中支持断点续传下载大文件
IE的自带下载功能中没有断点续传功能,要实现断点续传功能,需要用到HTTP协议中鲜为人知的几个响应头和请求头. 一. 两个必要响应头Accept-Ranges.ETag 客户端每次提交下 ...
- 简短介绍 C# 6 的新特性
几周前我在不同的地方读到了有关C#6的一些新特性.我就决定把它们都收集到一起,如果你还没有读过,就可以一次性把它们都过一遍.它们中的一些可能不会如预期那样神奇,但那也只是目前的更新. 你可以通过下载V ...