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());
//  }
  
 }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Java执行Shell脚本可以使用`Runtime`类或`ProcessBuilder`类。下面是使用`Runtime`类执行Shell脚本的示例代码: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ShellScriptExecutor { public static void main(String[] args) { try { // 执行Shell脚本命令 String command = "sh /path/to/script.sh"; Process process = Runtime.getRuntime().exec(command); // 获取Shell脚本输出结果 BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // 等待Shell脚本执行完成 int exitCode = process.waitFor(); System.out.println("Shell脚本执行完成,退出码:" + exitCode); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } } ``` 上述代码中,`/path/to/script.sh`是你要执行Shell脚本的路径。你可以将实际的Shell脚本路径替换到代码中。 使用`ProcessBuilder`类执行Shell脚本的示例代码如下: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ShellScriptExecutor { public static void main(String[] args) { try { // 执行Shell脚本命令 ProcessBuilder processBuilder = new ProcessBuilder("sh", "/path/to/script.sh"); Process process = processBuilder.start(); // 获取Shell脚本输出结果 BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // 等待Shell脚本执行完成 int exitCode = process.waitFor(); System.out.println("Shell脚本执行完成,退出码:" + exitCode); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } } ``` 同样,你需要将实际的Shell脚本路径替换到代码中。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

涂作权的博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值