项目需求,需要通过java调用shell脚本实现逻辑,但是又不想java服务绑定一个脚本,每次部署都得带着脚本,所以想实现Java写一个临时脚本,执行完就删掉(测试了下,shell脚本可以在自己脚本里删除自己)。
遇到的问题:
1. 换行问题
使用Java的IO流在写文件时,一行一行写,需要换行,就在每行后面拼上了\r\n,写出来发现不好使,后来找到System.getProperty("line.separator")方法,会根据系统类型生成系统自己的换行符,完美解决换行问题;
2. 编码问题
写出来文件,使用vim查看显示时[dos]编码,调用脚本会提示 No such file or directory,最后使用System.getProperty("file.encoding")获取系统编码,写入时将字符串进行编码设置,解决问题;
直接上代码:
public static String writeTempFile() throws IOException {
String filePath;
//创建临时文件
File file = new File("/temp/deal_business_" + System.currentTimeMillis() + ".sh");
//获取文件全路径,并且判断父目录是否存在,不存在通过mkdirs方法,创建目录
filePath = file.getPath();
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
Boolean result = true;
if (!file.exists()) {
//判断文件是否存在,不存在就创建文件
result = file.createNewFile();
}
if (result) {
log.info("文件路径:{}", filePath);
//使用try-with-resources进行流关闭
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
//获取系统编码
String fileEncode = System.getProperty("file.encoding");
//设置编码+添加换行符
bw.write(new String("#!/bin/sh".getBytes("UTF-8"), fileEncode) + System.getProperty("line.separator"));
bw.write(new String("#处理业务逻辑".getBytes("UTF-8"), fileEncode) + System.getProperty("line.separator"));
bw.write(new String("path=$1".getBytes("UTF-8"), fileEncode) + System.getProperty("line.separator"));
bw.write(new String("scriptFile=$2".getBytes("UTF-8"), fileEncode) + System.getProperty("line.separator"));
//-p :如果多级目录不存在,创建目录
bw.write(new String("mkdir -p /temp/produt/$path".getBytes("UTF-8"), fileEncode) + System.getProperty("line.separator"));
//cp -a 复制目录下所有内容,后面添加/. 会将目录下.开头的隐藏文件也一同复制过去,这里我们需要隐藏文件,所以一同复制过去了
bw.write(new String("cp -a /temp/beta/. /temp/produt/$path".getBytes("UTF-8"), fileEncode) + System.getProperty("line.separator"));
//业务逻辑...
//最后添加删除临时脚本目录,脚本路径在执行的时候通过参数传递进去
bw.write(new String("rm -rf $scriptFile".getBytes("UTF-8"), fileEncode) + System.getProperty("line.separator"));
bw.write(new String("echo ================= SUCCESS END".getBytes("UTF-8"), fileEncode);
//关闭流
bw.close();
log.info("生成临时文件成功");
} catch (Exception e) {
log.error("生成临时文件出现异常!", e);
} finally {
log.info("生成临时文件结束!");
}
}
//返回文件路径
return filePath;
}
java调用shell脚本:
参考我之前的一篇文章:java调用shell脚本及注意事项