背景:想使用 Java 里的 Apache common exec 工具包中的 CommandLine 执行 shell 文件,因为 shell 文件里有一行是使用虚拟环境下的 python 命令去执行 python 脚本,我们想动态的修改 python 后面跟随的参数。

1.shell 脚本(比如这里的参数是 JobName1)

#!/bin/bash
source /opt/xxc/flask_config.cfg
/opt/venv/bin/python /opt/xxc/dashboard/jobs/job.py JobName1
echo "End!"

2. 如上,我们想将 JobName1 改成 JobName2,同时写回到这个 shell 脚本里,脚本名字叫 run_script.sh。

import java.io.*;
 
public class Test {
    public static void main(String[] args) {
        String jobName = "JobName2";
        String filePath = "/opt/xxc/run_script.sh";
        String content = readFile(filePath, jobName);
        writeFile(filePath, content);
    }
 
    private static String readFile(String filePath, String jobName){
        String cmd = "/opt/venv/bin/python /opt/xxc/dashboard/jobs/job.py";
        BufferedReader br = null;
        String line;
        StringBuffer bufAll = new StringBuffer();
        try {
            br = new BufferedReader(new FileReader(filePath));
            while ((line = br.readLine()) != null) {
                StringBuffer buf = new StringBuffer();
                if (line.startsWith(cmd)) {
                    buf.append(cmd);
                    buf.append(" ").append(jobName);
                    buf.append(System.getProperty("line.separator"));
                }else {
                    buf.append(line);
                    buf.append(System.getProperty("line.separator"));
                }
                bufAll.append(buf);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (br != null) {
                try {
                    br.close();
                }catch (IOException e){
                    br = null;
                }
            }
        }
        return bufAll.toString();
    }
 
    private static void writeFile(String filePath, String content) {
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter(filePath));
            bw.write(content);
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (bw != null){
                try{
                    bw.close();
                }catch (IOException e) {
                    bw = null;
                }
            }
        }
    }
}

3. 上面的方法是先去读 shell 脚本,读的同时修改那一行代码,然后把 shell 内容重新组装成一个字符串,最后再塞到原文件中。执行后的结果是

#!/bin/bash
source /opt/xxc/flask_config.cfg
/opt/venv/bin/python /opt/xxc/dashboard/jobs/job.py JobName2
echo "End!"

参考:

  1. https://blog.csdn.net/qq_33643690/article/details/81737957 (转载)

  2. https://blog.csdn.net/silentwolfyh/article/details/74939703 (Java 的 RandomAccessFile 类实现,不太会用)

  3. https://blog.csdn.net/weixin_35653315/article/details/72886718 (python 传递参数的三种方式)

  4. https://blog.csdn.net/f45056231p/article/details/88692444 (java 获取路径)

  5. https://blog.csdn.net/qq_36769100/article/details/79373269 (java 获取系统路径分隔符)