【问题标题】:Running a shell script using process builder in java在java中使用进程构建器运行shell脚本
【发布时间】:2023-09-14 16:45:01
【问题描述】:

我正在尝试运行一个 shell 命令 - cat input.txt | shellscript.sh

如您所见,shell 脚本需要输入,所以我创建了一个输入 txt。

此命令在终端中运行良好。但我不确定它在 java 中是如何工作的。

为了完成这项工作,我制作了另一个名为 command.sh 的脚本,它只有这个 shell 命令 - cat input.txt | shellscript.sh

我把它们都放在同一个目录中。当我运行它时,没有错误,但脚本中的命令似乎没有运行。

      public class testing {

    public static void main(String[] args) throws IOException,InterruptedException {
    Process p = new ProcessBuilder("/bin/sh", "/Random Files/command.sh").start();



    }
}

知道如何让它工作吗?或者我可以直接调用命令 - cat input.txt | shellscript.sh 以某种方式使其工作? 另外你能告诉我如何获得输出吗?

【问题讨论】:

标签: java shell process processbuilder


【解决方案1】:

几个月前我使用以下代码进行了此操作,供您参考,可能会有所帮助。

要了解这两种方法之间的区别,请查看Difference between ProcessBuilder and Runtime.exec(),也可以查看ProcessBuilder vs Runtime.exec()

public class ShellCommandsHandler {
    private static final  Logger log = Logger.getLogger(ShellCommandsHandler.class);


    public static void execute(String script){

        try {
            Process p = Runtime.getRuntime().exec(script);

            BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line=null;

            while((line=input.readLine()) != null) {
                System.out.println(line);
            }

            int exitVal = p.waitFor();
            System.out.println("Exited with error code "+exitVal);
            log.debug(("Exited with error code "+exitVal));

        } catch(Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }

    public static void execute(String[] code){

        //String[] StringMklink = {"cmd.exe", "/c",  "mklink"+" "+"/j"+" "+"\"D:/ Games\""+" "+"\"D:/Testing\""};

        try{
            ProcessBuilder pb=new ProcessBuilder(code);
            pb.redirectErrorStream(true);
            Process process = pb.start();
            BufferedReader inStreamReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            while(inStreamReader.readLine() != null){
                System.out.println(inStreamReader.readLine());
            }
        } catch (IOException e) {
            System.out.println(e.toString());
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }

    public static void main(String[] args){
        execute("cmd.exe /c xcopy \"D:\\Downloads\\Temp\\data\\*.*\" \"D:\\Downloads\\\" /E");

    }

}

【讨论】:

    最近更新 更多