1

Possible Duplicate:
run shell command from java

I'm trying to run a process with some arguments from inside Java and before running the particular command I print it using println.

Now the problem is from inside Java, the process is not doing good.. its sending some error on the Error Stream instead of output. But If I run the same command printed by Java on screen in console, it works perfectly.

String command="abc -def -hhij";
System.out.println(command);
Process p = Runtime.getRuntime.exec(command);

Anyone know whats going on wrong?

Community
  • 1
  • 1
  • 2
    What error? Could it be an environment variable issue? What happens if you try a simple command like `pwd`? – Ted Hopp Dec 06 '11 at 05:29
  • I think something went wrong. What went wrong? – Nate W. Dec 06 '11 at 05:29
  • @Shakedown- Added more detail about what went wrong.. ;) –  Dec 06 '11 at 05:36
  • "Syntax error: ( unexpected". What parameters are you really using? Something probably needs to be escaped or quoted. – Thilo Dec 06 '11 at 05:38
  • @Thilo- The command with parameters as printed by JAVA is in the question and running this in console works. Also I'm printing using `println()` passing it the string properly escaped. –  Dec 06 '11 at 05:41

3 Answers3

2

The Runtime.exec(String) using the StringTokenizer, which doesn't know how to process quoted text. The simplest fix is to use the exec that accepts your parameters in an array.

String[] command={ "abc", "-def", "-hhij"};
Process p = Runtime.getRuntime.exec(command);
phatfingers
  • 9,770
  • 3
  • 30
  • 44
  • @phatfingers- I have added the output from ErrorStream in question.. –  Dec 06 '11 at 05:38
  • 1
    Try the form of exec that takes a String[] with each parameter as a separate String. Omit the quotes. – phatfingers Dec 06 '11 at 05:43
  • @phatfingers- Tried that.. still giving the same error. –  Dec 06 '11 at 06:17
  • Are the parentheses in "likes(john, marry)." the only parentheses in the statement, or are you substituting "[sample]." for some additional data not shown? – phatfingers Dec 06 '11 at 06:37
  • @pathfingers- It worked man... as you shown in answer. Previously, I modified it a little to invlude `"` in args, but that was not right. –  Dec 06 '11 at 07:13
  • Glad you're back in business! – phatfingers Dec 06 '11 at 07:18
1

I would try just to escape those '(' with \: '\\(' (double \ due to Java escaping rules)

Nikem
  • 5,716
  • 3
  • 32
  • 59
0

Most likely the command needs the full path to the command. C:\dir\abc.exe or whatever.

If it's a script make sure it' executed by the correct shell.

Tom
  • 43,583
  • 4
  • 41
  • 61