java执行shell命令

package com.pms.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 执行 linux命令
 *
 * @author mars
 *
 */
public class ExecuteLinux {

// log4j实例名
 private static final Log log = LogFactory.getLog(ExecuteLinux.class
   .getCanonicalName());

/**
  * 执行linux命令,并输出结果
  *
  * @param cmd
  * @throws RuntimeException
  * @throws IOException
  */
 public static void execute(String[] cmd) throws Exception {
  InputStream errorStream = null;
  InputStream inputStream = null ;
  Process ps = null;
  try {
   // String[] cmd = new String[] { "/bin/sh", "-c", "ls" };
   ps = Runtime.getRuntime().exec(cmd);
   log.debug("开始执行本地线程");
   
   errorStream = ps.getErrorStream(); // 正确结果的流
   inputStream = ps.getInputStream(); // 错误结果的流
   printError(errorStream);
   printInfo(inputStream);
   
  } catch (Exception e) {
   log.error("execute linux command error...", e);
   throw new Exception("execute linux command error...");
  }finally{
   if(errorStream != null){
    errorStream.close();
   }
   if(inputStream != null){
    inputStream.close();
   }
   
   ps.destroy();
  }
  
 }
 
 /**
  * 打印  正确信息
  * @param errorStream
  * @throws IOException
  */
 private static void printInfo(InputStream inputStream) throws IOException{
  
  StringBuffer sb = new StringBuffer();
  int line=0;
  while ((line = inputStream.read(new byte[1024])) != -1) {
   sb.append((char)line).append("\n");
  }
  String result = sb.toString();
  System.out.println("#####正确信息######:"+result);
  log.debug("#####正确信息LOG######:"+result);
 }
 
 /**
  * 打印错误信息
  * @param errorStream
  * @throws IOException
  */
 private static void printError(InputStream errorStream) throws IOException{
  
  StringBuffer sb = new StringBuffer();
  int line=0;
  while ((line = errorStream.read(new byte[1024])) != -1) {
   sb.append((char)line).append("\n");
  }
  String result = sb.toString();
  System.out.println("#####错误信息######:"+result);
  log.debug("#####错误信息LOG######:"+result);
 }
 
 /**
  * 获得 wgrib2 切割的linux命令,将grib2切割为二进制 bin 文件
  * @param pathName 文件路径名
  * @param fileName 文件名
  * @param savePath 要保存到的路径名
  * @param lists 条件集合(必不为空,因为从数据库获得,而存入数据库时,前台有校验不为空)
  * @return
  */
 public static String[] getLinuxCommand(String pathName, String fileName, String savePath, List<String> lists){
  
  //"/bin/sh", "-c",
  String[] cmd = new String[3];
  cmd[0] = "/bin/sh";
  cmd[1] = "-c";
  
  StringBuffer condition_bf = new StringBuffer();
  for (String str : lists) {
   condition_bf.append(str+" mb|");
  }
  // 将最后一个 ‘|‘ 符号截掉
  String condition_str = condition_bf.toString().substring(0, condition_bf.toString().length()-1);
  //wgrib2 -s
Z_NAFP_C_BABJ_20120508000000_P_CNPC-T639-GMFS-HNEHE-00300.grib2 | grep
-E "(\bHGT:20\b)|(\bHGT:30\b)" | wgrib2 -i
Z_NAFP_C_BABJ_20120508000000_P_CNPC-T639-GMFS-HNEHE-00300.grib2
-no_header -bin data5.bin
  StringBuffer bf = new StringBuffer();
  bf.append("wgrib2 -s ");
  bf.append(pathName+"/"+fileName);
  bf.append(" | grep -E ");
  bf.append("\""+condition_str+"\"");
  bf.append(" | wgrib2 -i ");
  bf.append(pathName+"/"+fileName);
  bf.append(" -no_header -bin ");
  String newName = fileName.substring(0, fileName.indexOf(".")); // 去掉 .grib2 的文件名
  bf.append(savePath+"/"+newName+".bin");
  cmd[2] = bf.toString();
  
  return cmd;
 }
 
 public static void main(String[] args) {
//  String str = "new.grib2";
//  System.out.println(str.substring(0, str.indexOf(".")));
//  
//  String pathName = "/home/ftp/cwfs";
//  String fileName = "new_003.grib2";
//  String savePath ="/home/ftp/cwfs";
//  
//  List<String> lists = new ArrayList<String>();
//  lists.add("HET:20");
//  String[] command = getLinuxCommand(pathName, fileName, savePath, lists);
//  
//  System.out.println(command[2]);
  
//  File file = new File("E:temp");
//  System.out.println(file.getParent());
//  File[] listFiles = file.listFiles();
//  if(listFiles != null && listFiles.length > 0){
//   for (File f : listFiles) {
//    f.delete();
//   }
//  }
  
//  File[] list = file.listFiles();
//  for (File s : list) {
//   System.out.println(s.getPath());
//  }
  
 }
}

时间: 2024-08-07 21:20:59

java执行shell命令的相关文章

java执行shell命令,chmod 777 xxx,改变权限无效的解决办法。

在java程序中执行shell命令,改变文件的权限,可以在命令行中执行 chmod 777 <span style="font-family: Arial, Helvetica, sans-serif;">/data/misc/123.sh"</span> 来改变权限,但是在java代码中执行这个命令时使用 Runtime.getRuntime().exec("chmod 777 /data/misc/123.sh"): 无效,使用

[Scala] Java执行Shell命令

Methods ProcessBuilder.start() 和 Runtime.exec() 方法都被用来创建一个操作系统进程(执行命令行操作),并返回 Process 子类的一个实例,该实例可用来控制进程状态并获得相关信息. The Runtime.exec(String) method takes a single command string that it splits into a command and a sequence of arguments. Process proces

java执行shell命令中有空格的处理方法

?Runtime.getRuntime().exec(cmdstring);如果此时cmdstring中的参数(例如cp文件时文件名)含有特殊符号空格,此时就会出现错误,因为源码会按照一些特殊字符(" \t\n\r\f",注意到其中含有空格)去切分cmdstring变为数组,所以有空格会导致错误,这种情况可以用命令数组实现,就是把cmdstring里的东西自己放到数组里,就不用源码去切分了就不会有问题,例: abc af.zip为一个文件名 cmdstring="cp abc

Java远程执行Shell命令

1. Jar包:ganymed-ssh2-build210.jar 2. 步骤: a) 连接: Connection conn = new Connection(ipAddr); conn.connect(); b)认证: boolean authenticateVal = conn.authenticateWithPassword(userName, password); c) 打开一个Session: if(authenticateVal) Session session = conn.op

Android JAVA代码执行shell命令

Android中级篇之用JAVA代码执行shell命令 [日期:2011-12-08] 来源:Linux社区  作者:y13872888163    在Android可能有的系统信息没有直接提供API接口来访问,为了获取系统信息时我们就要在用shell指令来获取信息,这时我们可以在代码中来执行命令 ,这里主要用到ProcessBuilder 这个类. 代码部分  : 1.package com.yin.system_analysis; 2.import java.io.File; 3.impor

Java 实现 ssh命令 登录主机执行shell命令

Java 实现 ssh命令 登录主机执行shell命令 1.SSH命令 SSH 为 Secure Shell 的缩写,由 IETF 的网络小组(Network Working Group)所制定:SSH 为建立在应用层基础上的安全协议.SSH 是较可靠,专为远程登录会话和其他网络服务提供安全性的协议.利用 SSH 协议可以有效防止远程管理过程中的信息泄露问题.SSH最初是UNIX系统上的一个程序,后来又迅速扩展到其他操作平台.SSH在正确使用时可弥补网络中的漏洞.SSH客户端适用于多种平台.几乎

Java执行Shell脚本“No such file or directory” (win-&gt;Linux)异常的可能原因

转自:http://blog.csdn.net/zlpdaisy/article/details/6134314 用Runtime.getRuntime().exec()方法执行Linux的一个Shell脚本时,报 Cannot run program "./script/abc.sh": java.io.IOException: error=2, No such file or directory] java.io.IOException: Cannot run program &q

Java执行shell脚本关闭远程数据库

本实例为用Java执行shell脚本启动或关闭远程Mysql数据库,需求原因:游戏服务器合服后,为了节省内存消耗,需要关闭合服后的服务器不必要的数据库(一台服务器主机存在多个MySql数据库),以提高服务器性能,但有时需要查询历史游戏玩家信息,又需要开启数据库,为了节省运维人员的人力和时间,游戏后台就提供非运维人员都可操作开关数据库的操作. 功能实现步骤: 第一:服务器后台提供参数,发送异步请求,请求方法如下 <script type="text/javascript">

Java调用Shell命令和脚本

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