YMI
YMI

Reputation: 165

Run Java app from Java with space in .jar file path

I'm trying to run Java CUP (Java version for LEX/YACC parser) from within a Java application.

This is the code I have (I copied most of it from the internet):

String command  = "java " +
                  "-jar " +
                  "\"g:My Documents\\Dropbox\\Final Project\\Code\\Mano CPU\\Inputs\\Parser\\java-cup-11a.jar\" " +
                  "-destdir " +
                  "\"g:\\My Documents\\Dropbox\\Final Project\\Code\\Mano CPU\\src\\Assembler\" " +
                  "\"G:\\My Documents\\Dropbox\\Final Project\\Code\\Mano CPU\\Inputs\\Assembler\\Assembler.cup\"";

Process p = Runtime.getRuntime().exec(command);
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
while(line!=null)
{
    System.out.println(line);
    line=reader.readLine();
}

When I run this command in the command prompt of Win 7 (Without escaping the back-slashes and double-quoutes), it gets executed. If I comment out everything after "-jar", I get the java options (Which is expected, as the command is illegal), so I know it can run.

My guess is that passing a path with spaces is the problem. I tried using String[], but I get the same results. Escaping the spaces causes an error as well.

Does anybody have any idea as to how I can solve this?

Thanks.

Upvotes: 2

Views: 1722

Answers (1)

matts
matts

Reputation: 6897

Looks like you're missing the first backslash in the path to your jar:

String command  = "java " +
                  "-jar " +
                  "\"g:My Documents\\Dropbox\\Final Project\\Code\\Mano CPU\\Inputs\\Parser\\java-cup-11a.jar\" " +

should be

String command  = "java " +
                  "-jar " +
                  "\"g:\\My Documents\\Dropbox\\Final Project\\Code\\Mano CPU\\Inputs\\Parser\\java-cup-11a.jar\" " +
                       ^^

Edit: millimoose pointed out that Runtime#exec(String) doesn't use the shell to invoke, so I checked the documentation and it apparently just uses a StringTokenizer to split on spaces. Java is gonna split your command arguments even though they're wrapped in double-quotes. So in addition to fixing the backslash issue above, you're going to need to use the form of exec which accepts a String[]. And you won't need to double-quote arguments containing spaces.

String[] command = new String[] {
                       "java",
                       "-jar",
                       "g:\\My Documents\\Dropbox\\Final Project\\Code\\Mano CPU\\Inputs\\Parser\\java-cup-11a.jar",
                       "-destdir",
                       "g:\\My Documents\\Dropbox\\Final Project\\Code\\Mano CPU\\src\\Assembler",
                       "G:\\My Documents\\Dropbox\\Final Project\\Code\\Mano CPU\\Inputs\\Assembler\\Assembler.cup",
                   };

Process p = Runtime.getRuntime().exec(command);

Upvotes: 3

Related Questions