Java 调用 Shell 命令

近日项目中有这样一个需求:系统中的外币资金调度完成以后,要将调度信息生成一个Txt文件,然后将这个Txt文件发送到另外一个系统(Kondor)中。生成文件自然使用OutputStreamWirter了,发送文件有两种方式,一种是用写个一个类似于FTP功能的程序,另外一种就是使用Java来调用Shell,在Shell中完成文件的发送操作。我们选择后一种,即当完成外币资金的调度工作后,用Java的OutputStreamWriter来生成一个Txt文件,然后用Java来调用Shell脚本,在Shell脚本中完成FTP文件到Kondor系统的工作。

以下为Java程序JavaShellUtil.java

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
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";

//发送文件到Kondor系统的Shell的文件名(绝对路径)
private static final String sendKondorShellName = basePath + "sendKondorFile.sh";

public 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);
pid.waitFor();
} 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");
} finally {
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;
}

}

以下是Shell脚本sendKondorFile.sh,该Shell脚本的作用是FTP文件到指定的位置:

#!/bin/sh

#日志文件的位置

logFile="/opt/fms2_kondor/sendKondorFile.log"

#Kondor系统的IP地址,会将生成的文件发送到这个地址

kondor_ip=192.168.1.200

#FTP用户名

ftp_username=kondor

#FTP密码

ftp_password=kondor

#要发送的文件的绝对路径

filePath=""

#要发送的文件的文件名

fileName=""

#如果Shell命令带有参数,则将第一个参数赋给filePath,将第二个参数赋给fileName

if [ $# -ge "1" ]

then

filePath=$1

else

echo "没有文件路径"

echo "没有文件路径\n" >

>

$logFile

return

fi

if [ $# -ge "2" ]

then

fileName=$2

else

echo "没有文件名"

echo "没有文件名\n" >

>

$logFile

return

fi

echo "要发送的文件是 ${filePath}/${fileName}"

cd ${filePath}

ls $fileName

if (test $? -eq 0)

then

echo "准备发送文件:${filePath}/${fileName}"

else

echo "文件 ${filePath}/${fileName} 不存在"

echo "文件 ${filePath}/${fileName} 不存在\n" >

>

$logFile

return

fi

ftp -n ${kondor_ip} <

<

_end

user ${ftp_username} ${ftp_password}

asc

prompt

put $fileName

bye

_end

echo "`date +%Y-%m-%d‘ ‘%H:%M:%S` 发送了文件 ${filePath}/${fileName}"

echo "`date +%Y-%m-%d‘ ‘%H:%M:%S` 发送了文件 ${filePath}/${fileName}\n" >

>

$logFile

调用方法为:

JavaShellUtil javaShellUtil = new JavaShellUtil();

//参数为要执行的Shell命令,即通过调用Shell脚本sendKondorFile.sh将/temp目录下的tmp.pdf文件发送到192.168.1.200上

int success = javaShellUtil.executeShell("sh /tmp/sendKondorFile.sh /temp tmp.pdf");

时间: 2024-08-07 18:18:37

Java 调用 Shell 命令的相关文章

Java调用Shell命令和脚本

1.介绍 有时候我们在Linux中运行Java程序时,需要调用一些Shell命令和脚本.而Runtime.getRuntime().exec()方法给我们提供了这个功能,而且Runtime.getRuntime()给我们提供了以下几种exec()方法: Process exec(String command) 在单独的进程中执行指定的字符串命令. Process exec(String[] cmdarray) 在单独的进程中执行指定命令和变量. Process exec(String[] cmd

Java调用Shell命令和脚本,致力于hadoop/spark集群

前言 说明的是,本博文,是在以下的博文基础上,立足于它们,致力于我的大数据领域! http://kongcodecenter.iteye.com/blog/1231177 http://blog.csdn.net/u010376788/article/details/51337312 http://blog.csdn.net/arkblue/article/details/7897396 第一种:普通做法 首先,编号写WordCount.scala程序. 然后,打成jar包,命名为WC.jar.

java调用shell命令及脚本

shell脚本在处理文本及管理操作系统时强大且简单,将shell脚本结合到应用程序中则是一种快速实现的不错途径本文介绍使用java代码调用并执行shell 我在 -/bin/ 目录下写了jbossLogDelivery.sh,有两个功能{./jbossLogDelivery.sh list} 作用是输出jboss现有的日志列表,{./jbossLogDelivery.sh get logName [email protected]} 作用是将指定的日志发送到指定的邮箱 我在一个web程序中打算整

java001-java调用shell命令和脚本

一.项目需求: 从某一机构获取证书,证书机构提供小工具,执行.sh脚本即可启动服务,本地调用该服务即可获取证书. 问题:linux服务器启动该服务,不能关闭.一旦关闭,服务即停止. 解决方案:java调用shell命令,利用spring容器启动即执行方案. 参考博文:http://zohan.iteye.com/blog/1709136 项目结构: 原码: 1.RuntimeUtils.java 1 package com.csvalue.common; 2 3 import org.sprin

JAVA调用Shell脚本

在实际项目中,Java有时候需要调用C写出来的东西,除了JNI以外,我认为一种比较好的方法是JAVA调用Shell.先把C写出来的make成可执行文件,然后再写一个shell脚本执行该可执行文件,最后是JAVA调用该shell脚本. JAVA调用很简单,例子如下: 首先是shell脚本 [plain] view plain copy print? #!/bin/sh echo Begin word cluster /home/felven/word2vec/word2vec -train /ho

在android程序中调用shell命令与脚本

最近做android的一个功能就是调用shell命令来进行一些系统级别的操作,比如说是关机开机之类的,现在总结一下具体的用法以及遇到的坑(基于我所用到的,没用到的我就不说了) (1) Runtime.getRuntime().exec("ls"); 这是最简单的一种,你输入后就能就会执行ls命令,如果要获得输出的话可以这样写 Process p = Runtime.getRuntime().exec("ls"); String data = null; Buffer

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

Java 调用 shell 脚本详解

这一年的项目中,有大量的场景需要Java 进程调用 Linux的bash shell 脚本实现相关功能. 从之前的项目中拷贝的相关模块和网上的例子来看,有个别的"陷阱"造成调用shell 脚本在某些特殊的场景下,有一些奇奇怪怪的bug. 大家且听我一一道来. 先看看网上搜索到的例子: [java] view plain copy package someTest; import java.io.BufferedReader; import java.io.IOException; im

Java调用Linux命令执行

调用方式 Java调用linux命令执行的方式有两种,一种是直接调用linux命令,一种是将linux命令写到.sh脚本中,然后调用脚本执行. 详细说明 直接调用:使用java中lang包下面的Runtime类和Process类,其中Runtime类中的Runtime.getRuntime().exec(linux command)方法可以直接执行linux命令,而Process类可以接收Runtime.getRuntime().exec()类的返回值,并提供了waitFor()方法和destr