Java 调用 Shell 命令_process pid = null_易水寒82的博客-程序员宅基地

技术标签: Java  Shell  

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

以下为Java程序JavaShellUtil.java:

package cn.com.huixin.shell;

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");

 

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u013449380/article/details/90551212

智能推荐

鼠标消息处理-程序员宅基地

鼠标操作是Windows的重要内容,为了下一章用鼠标作图,本章先作一些基础知识的铺垫,以免下一章新内容太多。前面章节已经说过,窗口函数总共处理消息结构体中的三个内容,即message、wParam、lParam,其中message是主消息,wParam、lParam许多场合都不用,也就是值为0。有的消息只体用wParam、lParam的一个,不过键盘鼠标消息传递的信息比较多,wParam、lPar

oa服务器怎么一直维护,OA系统怎么维护?_余海晨的博客-程序员宅基地

访问量:512编辑:wangkang日期:2014-10-21 14:57:07OA系统怎么维护?随着计算机技术和网络科技的发展,OA系统的开发技术不断提高、更新;同时企业也处于一个不断运行发展的状态,企业的项目、部门、岗位、业务流程等都会发生不同的变化,要实现更高水平自动化办公,实现办公简易性、通用性、稳定性、可扩展性,使OA系统在不断变化的社会以及企业环境中,满足企业各部门的需求和发展,所以O..._停用oa系统服务器,请各部门做好

C#中将图片文件转化为二进制数组-用于数据库存储-程序员宅基地

在项目开发中,使用SQL Server存储数据,数据类型image可以保存图片。但是在存储之前需要将图片转化为二进制数组的形式进行赋值。将图片文件转换为二进制数组/// <summary> /// 将图片文件转换为二进制数组 /// </summary> /// <param name=”picpath”>图片路径</p..._c#将大量图片转化二进制

Linux笔记_关闭 防火墙 和 SELINUX-程序员宅基地

1、查看防火墙的状态 $ sudo service iptables status2、关闭防火墙 $ sudo service iptables stop3、启动防火墙 $ sudo service iptables start4、永久性设置防火墙 关闭 | 开启 $ sudo chkc

MasOS10.13.4安装Apache Tomcat/9.0.8_apache tomcat 9.0.8 漏洞-程序员宅基地

0、安装过程参考自:mac Tomcat9.0.1的安装1、下载Tomcat,地址:https://tomcat.apache.org/download-90.cgi 选择自己需要的,这里选择tar.gz2、在/Users/mac下建一个名为JavaTomcat的文件夹,解压后拷贝bin地址3、依次执行以下命令:(替换为自己的存放地址)sudo chmod u+x /Users/mac/Ja..._apache tomcat 9.0.8 漏洞

python处理声音_python 清音浊音处理-程序员宅基地

https://www.cnblogs.com/wpbing/p/9322872.html_python 清音浊音处理

随便推点

vue导出excel文件,wps提示无法打开文件,【responseType: ‘blob‘ 】_vue 下载excal wps无法显示_eadela的博客-程序员宅基地

vue导出excel文件,wps提示无法打开文件,【responseType: 'blob' 】_vue 下载excal wps无法显示

自定义拦截器的执行顺序_拦截器链的执行顺序怎么定义-程序员宅基地

一、正常放行情况1.第一个拦截器实现:package springboot.example.interceptor;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Com..._拦截器链的执行顺序怎么定义

Linux 中shell程序常用通配符-程序员宅基地

*:匹配 0 或多个字符?:匹配任意一个字符[list]:匹配 list 中的任意单一字符[!list]:匹配 除list 中的任意单一字符以外的字符[c1-c2]:匹配 c1-c2 中的任意单一字符 如:[0-9] [a-z]{string1,string2,...}:匹配 string1 或 string2 (或更多)其一字符串{c1..c2}:匹配 c1-c2 中全部字符 如{1..10}...

ccwow服务器维护,牧师 - 军团再临 - 178魔兽世界_菏何的博客-程序员宅基地

牧师职业大厅军团再临资料片中最大的改动便是神器和职业大厅了,如同德拉诺版本的要塞系统一样,7.0的职业大厅便像是一个强化版的要塞,不过在这里你不再是一个人,相同职业的玩家都会和你在一起来共同探索破碎群岛对抗燃烧军团。那让我们走进虚空之光神殿,一起来看看牧师的职业大厅虚空之光神殿。如何进入职业大厅在完成了登陆破碎群岛的起始任务后 我们到达拉然会接到。跟着任务线完成解锁第一把神器后返回达拉然找先知维纶..._cc军团再临

hadoop入门 启动 journalnode报错_cannot set priority of journalnode process 1336_modi_2020的博客-程序员宅基地

启动journalnode报错如下[hadoop@salve001 ~]$ hdfs --daemon start journalnodeERROR: Cannot set priority of journalnode process 74165[hadoop@salve001 ~]$查看报错日志提示2021-02-03 10:42:05,421 ERROR org.apache.hadoop.hdfs.qjournal.server.JournalNode: Failed to s._cannot set priority of journalnode process 1336

推荐文章

热门文章

相关标签