0

i'm trying to run shell command in linux via java. most of the commands work, but when i run the following command i get an execption, although it works in the shell:

    String command = "cat b.jpg f1.zip > pic2.jpg";

    String s = null;
    try {
        Process p = Runtime.getRuntime().exec(command);

        BufferedReader stdInput = new BufferedReader(new
             InputStreamReader(p.getInputStream()));

        BufferedReader stdError = new BufferedReader(new
             InputStreamReader(p.getErrorStream()));

        System.out.println("Here is the standard output of the command:\n");

        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }
        System.out.println("Here is the standard error of the command (if any):\n");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }
        System.exit(0);
    }
    catch (IOException e) {
        System.out.println("exception happened - here's what I know: ");
        e.printStackTrace();
        System.exit(-1);
    }

i am getting the error in the console:

cat: >: No such file or directory

cat: pic2.jpg: No such file or directory

  • 4
    I think this might be related - http://stackoverflow.com/questions/16238714/runtimes-exec-method-is-not-redirecting-the-output – Mirec Miskuf Dec 15 '15 at 16:10

3 Answers3

2

The problem is the redirection.

cat: >: No such file or directory

The way to interpret this error message:

  • the program cat is trying to tell you about a problem
  • the problem is that there is no file named >

Indeed, > is not a file. It's not intended as a file, at all. It's a shell operator to redirect output.

You need to use ProcessBuilder to redirect:

ProcessBuilder builder = new ProcessBuilder("cat", "b.jpg", "f1.zip");
builder.redirectOutput(new File("pic2.jpg"));
Process p = builder.start();
janos
  • 120,954
  • 29
  • 226
  • 236
1

Because you need to start a shell (e.g. /bin/bash) which will execute your shell command, replace:

String command = "cat b.jpg f1.zip > pic2.jpg";

with

String command = "bash -c 'cat b.jpg f1.zip > pic2.jpg'";
Adam Siemion
  • 15,569
  • 7
  • 58
  • 92
1

When you run a command it doesn't start a shell like bash unless you do this explicitly. This means you are running cat with four arguments b.jpg f1.zip > pic2.jpg The last two files names don't exist so you get an error.

What you are likely to have intended was the following.

String command = "sh -c 'cat b.jpg f1.zip > pic2.jpg'";

This will run sh which in sees > as a special character which redirects the output.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130