1

I've been trying to use Java to execute Microsoft Excel in the coding by using the following code:

Process pro = Runtime.getRuntime().exec("open -a Microsoft"+"\\"+" "+"Excel");
pro.waitFor();

When I print this command out, it is exactly what I use to start a Excel in the command line manually, but when I want to start it by using java runtime, it is not working. I know in the Microsoft Windows command line there's no such problem, but in Mac is there any other way to start a program by using java code?

I also tried to start a Calculator by using the same code like:

Process pro = Runtime.getRuntime().exec("open -a Calculator");

It works perfectly, is it because the space between the "Microsoft" and "Excel"?

4

1 回答 1

2

java.lang.Runtime.exec(String) parses the command line into single arguments itself and does not know anything about shell metacharacters such as using \ to quote a space character that's supposed to go into an argument.

Try doing the argument splitting yourself instead:

String[] cmdline = { "open", "-a", "Microsoft Excel" };
Runtime.getRuntime.exec(cmdline);

Note that you shouldn't need (or be able to) use a backslash to escape the space in the third element. When you type the command on the command line, that backslash is eaten by the shell as it splits the line into arguments to pass to the open program, but Runtime.exec() starts processes directly without the intervention of a shell, so if you put a backslash there, open would be able to see it, and would be confused by it.

于 2012-11-01T00:21:30.307 回答