0

I have a method

final ProcessBuilder processBuilder = new ProcessBuilder(this.cmd);
        processBuilder.redirectErrorStream(true);
        try {
            final Process process = processBuilder.start();
            try (final BufferedReader reader =
                         new BufferedReader(
                                 new InputStreamReader(
                                         process.getInputStream()
                                 )
                         )
            ) {
                while (reader.ready()) {
                    System.out.println(reader.readLine());
                }
                process.waitFor(this.timeOut, TimeUnit.SECONDS);
            }
        } catch (final Exception exc) {
            throw new IllegalStateException("Terminal command execution exception", exc);
        }

This method takes cmd(array of strings) from Constructor and then executes it. This is the value of cmd

new String[]{"cat","$(cat /home/Downloads/tmp/aqnYtUSVFp.txt)",">","/home/Downloads/hello.ts"}

So the whole command is looks like this cat $(cat home/Downloads/tmp/aqnYtUSVFp.txt) > /home/Downloads/hello.ts It works fine if I run it within terminal , but ProcessBuilder shows me the following error

cat: '$(cat /home/Downloads/aqnYtUSVFp.txt)': No such file or directory
cat: '>': No such file or directory
cat: /home/Downloads/hello.ts: No such file or directory

What did I miss . Why ProccBuilder doesn't recognize this command ?

Almas Abdrazak
  • 3,209
  • 5
  • 36
  • 80
  • 2
    Handling sub shells and redirection is the job for a shell such as sh or bash. `cat does not know how to do that. You probably want to execute `/bin/sh` with appropriate arguments. – Roger Lindsjö Jun 26 '19 at 14:01
  • @RogerLindsjö great idea I will do it and post my answer – Almas Abdrazak Jun 26 '19 at 14:03
  • 1
    ProcessBuilder (since j7) _can_ handle simple redirections, but with method calls not tokens in the command; see the javadoc. It (still) can't handle shell-type pipes, or variables or command substitution -- although this particular one could be replaced by `new String(Files.readAllBytes(Paths.get(filename))) .trim() .split("[ \t\n]+")` – dave_thompson_085 Jun 26 '19 at 15:34
  • Are you simply experimenting with class `ProcessBuilder` in order to understand how it works? Or are you trying to copy file `aqnYtUSVFp.txt` to file `hello.ts`? – Abra Jun 26 '19 at 17:14

0 Answers0