views:

220

answers:

3

Hi all,

I have a program which calls a shell command. When I executes the command using java's run.exec, it is not working but when I executes the command directly in terminal, it works like charm.

ex: pdf2swf "3bbba47.pdf" -T 9 -o "3bbba47.swf" didnt worked
    from java program but worked directly executing it in terminal.

But when I tried removing the quotes from the command

pdf2swf 3bbba47.pdf -T 9 -o 3bbba47.swf

It worked fine in both run.exec and terminal.

Why is it so?

I tried in both mac and ubuntu and ended with same result.

+2  A: 

run.exec() does not invoke the shell. The shell parses the command line and effectively removes the quotes before passing them as arguments to pdf2swf. You can only run "raw" commands with run.exec().

You can, if you want, run the shell with run.exec(), and have it parse your command as a shell command. Quoting will be a bit painful, but doable.

Ville Laurikari
+1  A: 

When you are in the shell, the quote character is interpreted before the shell give it to the JVM.

When you are in run.exec, the quotes are considered part of the command, so JVM believes that you ask for ["3bbba47.pdf"] instead of [3bbba47.pdf]

LDU
A: 

From: http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=1

Runtime.exec() is not a command line

One final pitfall to cover with Runtime.exec() is mistakenly assuming that exec() accepts any String that your command line (or shell) accepts. Runtime.exec() is much more limited and not cross-platform. This pitfall is caused by users attempting to use the exec() method to accept a single String as a command line would. The confusion may be due to the fact that command is the parameter name for the exec() method. Thus, the programmer incorrectly associates the parameter command with anything that he or she can type on a command line, instead of associating it with a single program and its arguments.

Arne