0

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"

0

4 Answers 4

1

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"}); 
Sign up to request clarification or add additional context in comments.

Comments

1

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"});

Comments

0
Runtime.getRuntime().exec

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

Comments

0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.