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

   以下为Java程序JavaShellUtil.java

  1. import java.io.BufferedReader;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.io.OutputStream;
  7. import java.io.OutputStreamWriter;
  8. import java.text.DateFormat;
  9. import java.text.SimpleDateFormat;
  10. import java.util.Date;
  11.  
  12. public class JavaShellUtil {
  13. //基本路径
  14. private static final String basePath = "/tmp/";
  15.  
  16. //记录Shell执行状况的日志文件的位置(绝对路径)
  17. private static final String executeShellLogFile = basePath + "executeShell.log";
  18.  
  19. //发送文件到Kondor系统的Shell的文件名(绝对路径)
  20. private static final String sendKondorShellName = basePath + "sendKondorFile.sh";
  21.  
  22. public int executeShell(String shellCommand) throws IOException {
  23. int success = 0;
  24. StringBuffer stringBuffer = new StringBuffer();
  25. BufferedReader bufferedReader = null;
  26. //格式化日期时间,记录日志时使用
  27. DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS ");
  28.  
  29. try {
  30. stringBuffer.append(dateFormat.format(new Date())).append("准备执行Shell命令 ").append(shellCommand).append(" \r\n");
  31.  
  32. Process pid = null;
  33. String[] cmd = {"/bin/sh", "-c", shellCommand};
  34. //执行Shell命令
  35. pid = Runtime.getRuntime().exec(cmd);
  36. if (pid != null) {
  37. stringBuffer.append("进程号:").append(pid.toString()).append("\r\n");
  38. //bufferedReader用于读取Shell的输出内容 bufferedReader = new BufferedReader(new InputStreamReader(pid.getInputStream()), 1024);
  39. pid.waitFor();
  40. } else {
  41. stringBuffer.append("没有pid\r\n");
  42. }
  43. stringBuffer.append(dateFormat.format(new Date())).append("Shell命令执行完毕\r\n执行结果为:\r\n");
  44. String line = null;
  45. //读取Shell的输出内容,并添加到stringBuffer中
  46. while (bufferedReader != null &
  47. &
  48. (line = bufferedReader.readLine()) != null) {
  49. stringBuffer.append(line).append("\r\n");
  50. }
  51. } catch (Exception ioe)
  52. stringBuffer.append("执行Shell命令时发生异常:\r\n").append(ioe.getMessage()).append("\r\n");
  53. } finally {
  54. if (bufferedReader != null) {
  55. OutputStreamWriter outputStreamWriter = null;
  56. try {
  57. bufferedReader.close();
  58. //将Shell的执行情况输出到日志文件中
  59. OutputStream outputStream = new FileOutputStream(executeShellLogFile);
  60. outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
  61. outputStreamWriter.write(stringBuffer.toString());
  62. } catch (Exception e) {
  63. e.printStackTrace();
  64. } finally {
  65. outputStreamWriter.close();
  66. }
  67. }
  68. success = 1;
  69. }
  70. return success;
  71. }
  72.  
  73. }

以下是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");

Java 调用 Shell 命令的更多相关文章

  1. java基础/java调用shell命令和脚本

    一.项目需求: 从某一机构获取证书,证书机构提供小工具,执行.sh脚本即可启动服务,本地调用该服务即可获取证书. 问题:linux服务器启动该服务,不能关闭.一旦关闭,服务即停止. 解决方案:java ...

  2. Hadoop概念学习系列之Java调用Shell命令和脚本,致力于hadoop/spark集群(三十六)

    前言 说明的是,本博文,是在以下的博文基础上,立足于它们,致力于我的大数据领域! http://kongcodecenter.iteye.com/blog/1231177 http://blog.cs ...

  3. java 调用shell命令

    原文:http://kongcodecenter.iteye.com/blog/1231177 Java通过SSH2协议执行远程Shell脚本(ganymed-ssh2-build210.jar)   ...

  4. java调用shell命令及脚本

    shell脚本在处理文本及管理操作系统时强大且简单,将shell脚本结合到应用程序中则是一种快速实现的不错途径本文介绍使用java代码调用并执行shell 我在 -/bin/ 目录下写了jbossLo ...

  5. java 执行shell命令遇到的坑

    正常来说java调用shell命令就是用 String[] cmdAry = new String[]{"/bin/bash","-c",cmd} Runtim ...

  6. Java 调用 shell 脚本详解

    这一年的项目中,有大量的场景需要Java 进程调用 Linux的bash shell 脚本实现相关功能. 从之前的项目中拷贝的相关模块和网上的例子来看,有个别的“陷阱”造成调用shell 脚本在某些特 ...

  7. JAVA调用SHELL事例

    以往一直都是crontab+shell调用java程序,最近需要反过来,使用java调用shell程序,实现定时管理,今天总结一下. 基础内容: java的java.lang.Runtime类提供了e ...

  8. [转载]JAVA调用Shell脚本

    FROM:http://blog.csdn.net/jj12345jj198999/article/details/11891701 在实际项目中,JAVA有时候需要调用C写出来的东西,除了JNI以外 ...

  9. Java调用Linux命令执行

    调用方式 Java调用linux命令执行的方式有两种,一种是直接调用linux命令,一种是将linux命令写到.sh脚本中,然后调用脚本执行. 详细说明 直接调用:使用java中lang包下面的Run ...

随机推荐

  1. java的main函数组成

    package test;/*public static void main(String[] args)主函数特殊之处:1.格式是固定的2.被jvm(虚拟机)所识别和调用 public:因为权限必须 ...

  2. type-of-python作业-判断字符串是否属于回文需要忽略其中的标点、空格与大小写

    type-of-python作业 作业练习:要想检查文本是否属于回文需要忽略其中的标点.空格与大小写.例如,"Rise to vote, sir."是一段回文文本,但是我们现有的程 ...

  3. MySQL数据库语句

    一 . 常用mysql命令行命令        1 .启动MYSQL服务   net start mysql 停止MYSQL服务   net stop mysql 2 . netstat –na | ...

  4. OpenGL之纹理贴图(Texture)

    学习自: https://learnopengl-cn.github.io/01%20Getting%20started/06%20Textures/ 先上一波效果图: 实际上就是:画了一个矩形,然后 ...

  5. Linux系统上安装、卸载JAVA、TOMCAT的方法

    一. 安装JAVA 安装方法1:手工上传 创建安装目录上传JAVA安装包 Normal 0 7.8 磅 0 2 false false false EN-US ZH-CN X-NONE /* Styl ...

  6. Java中栈的应用,括号匹配

    package edu.yuliang.Data_Structure_Basics; import org.omg.PortableInterceptor.SYSTEM_EXCEPTION; /* 给 ...

  7. Matlab R2015b_@Ubuntu 16_安装备忘

    1.下载解压包解压 2.cd 进入文件夹,使用 sh 打开,安装过程中不要使用“网络激活” 3.mv Crack文件中的 /R2015b/bin/glnxa64 里面的三个lib*.so 到Matla ...

  8. Android大作业

    1.项目成员 邓乾尧 学号:1600802005 班级:161  博客:http://www.cnblogs.com/2575590018dqy/ 韦家城 学号:1600802026 班级:161  ...

  9. centos7.5 时间设置

    # ----- 设置时间同步+时区(上海) ----- rpm -qa ntp || yum -y install ntp systemctl enable ntpd timedatectl set- ...

  10. ubuntu18.04LTS修改键盘键位

    在Linux中为了敲命令方便,所以需要做一下键盘键位调整: 1.Esc键和`(即数字键1前面的那个键)对换: 2.Caps Lock键和左Control键对换: 编辑键位文件: sudo vim /u ...