使用java

时间:2015-10-27 05:48:58

标签: java shell process processbuilder

我正在尝试运行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以某种方式让它工作? 还能告诉我如何获得输出吗?

1 个答案:

答案 0 :(得分:0)

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

要了解两种方法之间的区别,请看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");

    }

}