birdcage
birdcage

Reputation: 2676

Can't run commands in java code

Im trying to run multiple shell commands in java. Here is my code:

Process send = Runtime.getRuntime().exec(new String[] {"javac /tmp/"+ fileName + ";" + "sed -i 's/Foo/Foo2/g' /tmp/"+ fileName + ";" + "java /tmp/"+ fileNameShort + ".class;"}); 

I know the files are there exactly under tmp folder but none of them works fine.

filename: "Foo.java" fileNameShort: "Foo"

Upvotes: 0

Views: 192

Answers (4)

Akira
Akira

Reputation: 4071

You can run 3 commands in a row like you are doing, but then you need to pass them to a bash (or another shell) to run. As other people pointed out, you can only start one OS process per exec() call. So make this process a bash and give it the means to run the processes you need. Or simply start 3 processes as another user pointed out.

Then your problem becomes a bash one.

For instance, the following:

echo -e "echo 'AAA'; for x in 1 2 3; do echo 'BBB'; done; echo 'CCC'" | bash

Will print

AAA
BBB
BBB
BBB
CCC

Those are actually 3 processes that you can run all that in a single exec().

Now, about the problem you are actually trying to solve, it looks like you want to change bytecodes. I would recommend using a library for that. Take a look at ASM: http://asm.ow2.org/

Upvotes: 0

pobrelkey
pobrelkey

Reputation: 5973

You're executing three commands in a row. Each command should be a separate Process. Also, the command and the parameters should be broken out into elements of the array:

Process send1 = Runtime.getRuntime().exec(new String[] {"javac", "/tmp/"+ fileName});
send1.waitFor();  // this returns an int with the exit status of the command - you really should check this!
Process send2 = Runtime.getRuntime().exec(new String[] {"sed", "-i", "s/Foo/Foo2/g", "/tmp/"+ fileName});
send2.waitFor();
Process send3 = Runtime.getRuntime().exec(new String[] {"java", "/tmp/"+ fileNameShort+".class"});
send3.waitFor();

Alternately, feed the whole thing to sh -c (though you really, really should use the previous method as then you don't have to worry about escaping arguments etc.)

Process send = Runtime.getRuntime().exec(new String[] {"sh", "-c", "javac /tmp/"+ fileName + "; sed -i 's/Foo/Foo2/g' /tmp/"+ fileName + "; java /tmp/"+ fileNameShort + ".class"}); 

Upvotes: 1

anubhava
anubhava

Reputation: 785146

No you cannot do that since this method:

Executes the specified string command in a separate process.

It is better to create a shell script and call that script:

Process pr = Runtime.getRuntime().exec(new String[]{"/bin/bash", "-c", "/path/script.sh"});

Upvotes: 1

Artur
Artur

Reputation: 7257

Runtime.getRuntime().exec

is not your command line - you cannot handle few commands at the same time, cannot use redirects etc...

Upvotes: 0

Related Questions