项目中,需要通过java 调用shell
下面提供shell 的工具类
package com.myjz.util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
/**
* java 调用shell文件
*/
public class ShellUtils {
/**
* 执行下载文件的shell
* @param shellFileName shell 文件名称
* @param downFileName 下载文件的名称 --- 传入shell 的参数
* @return
*/
public static Map<String,Object> exeShellDownFile(String shellFileName,String downFileName){
Map<String,Object> result = new HashMap<String,Object>();
String osname = System.getProperty("os.name");
String shellPath = getShellPath(osname);
System.out.println("当前的操作系统是:"+osname);
ProcessBuilder builder;
if((null != osname) && osname.toLowerCase().startsWith("win")) {
//windows 操作系统
builder = new ProcessBuilder("cmd","/c",shellPath+"/"+shellFileName,downFileName);
}else {//Linux
builder = new ProcessBuilder("/bin/sh",shellPath+"/"+shellFileName,downFileName);
}
int runningStatus = 0;
String s = null;
StringBuffer sb = new StringBuffer();
BufferedReader stdInput = null;
BufferedReader stdError = null;
try {
Process p = builder.start();
stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while((s = stdInput.readLine()) != null) {
System.out.println("shell log :"+ s);
sb.append(s);
}
while((s = stdError.readLine()) != null) {
System.out.println("shell error log :"+ s);
sb.append(s);
}
try {
runningStatus = p.waitFor();
}catch (Exception e) {
runningStatus = 1;
sb.append(e.getMessage());
System.out.println("等待shell 执行反馈时,报错");
e.printStackTrace();
}
}catch (Exception e) {
runningStatus = 1;
sb.append(e.getMessage());
System.out.println("执行下shell 文件,报错");
e.printStackTrace();
} finally {
closeStream(stdInput);
closeStream(stdError);
}
System.out.println("执行状态为:"+runningStatus);
if(runningStatus == 0) {
result.put("code", "1");
result.put("msg", "执行成功");
}else {
result.put("code", "0");
result.put("msg", "执行shell失败:"+sb.toString());
}
return result;
}
private static String getShellPath(String osname) {
// TODO Auto-generated method stub
return "D://";
}
private static void closeStream(BufferedReader reader) {
try {
if(reader != null) {
reader.close();
}
} catch (Exception e) {
reader = null;
}
}
public static void main(String[] args) {
exeShellDownFile("downFileShell.sh", "test.pdf");
}
}
特意去看了
new ProcessBuilder() 的构造方法的源码
内部的逻辑其实很简单,第一个参数为执行方法,后面的参数就是进行参数加空格拼接
如:ProcessBuilder builder = new ProcessBuilder("/bin/sh","/home/user/downFileShell.sh","test.pdf","20230101");
最后组成的 shell 执行语句 :
/bin/sh /home/user/downFileShell.sh test.pdf 20230101
test.pdf 作为第一个参数
20230101 作为第二个参数
多参数,依次类推
shell 中获取参数的方式 顺带一笔
fileName=$1
exeDate=$2
echo $fileName
echo $exeDate
输出就是:
test.pdf
20230101