-2
Process log_remover = Runtime.getRuntime().exec("echo \"bleh\" > test.txt");
log_remover.waitFor();
log_remover.destroy();

this does nothing

Process node_creation = Runtime.getRuntime().exec("cp -r ../HLR"+String.valueOf(count-1)+" ../HLR"+String.valueOf(count));
node_creation.waitFor();
node_creation.destroy();

however this works :S

Atish Deepank
  • 17
  • 1
  • 6

3 Answers3

1

The redirection works only if a shell is used. Runtime.exec() does not use a shell.

See Java Executing Linux Command

Community
  • 1
  • 1
user1225148
  • 116
  • 2
1

Redirection is handled by a shell, and you're not invoking a shell here, so you can't use redirection. Something like this, on the other hand, would work:

Runtime.getRuntime().exec(new String[] {"sh",  "-c", "echo 'bleh' > text.txt"});

Note I've changed this to use the form of exec() that takes an array of Strings, as properly tokenizing quoted strings on a command line is something else that only the shell can do!

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
0

Classic mistake I've seen many times before...

The first argument to Runtime.getRuntime().exec() is the executable, so your code is trying to execute a command literally called echo \"bleh\" > test.txt, but it should be trying to execute echo. Arguments to executables are passed in after the executable, like this:

Runtime.getRuntime().exec("echo", new String[]{"bleh"});

Redirecting output is another story, because the *nix operator > is a shell thing. To replicate this in java you have to get the outputstream of the command and pump it to the inputstream of another process

Bohemian
  • 412,405
  • 93
  • 575
  • 722