knowme
knowme

Reputation: 417

Executing jar file in java

i'm executing a jar file in java. so far my code works perfectly.

im executing epubcheck via java because its a console application

here is the address of the epubcheck

https://github.com/IDPF/epubcheck

except when the name of the file that i need to browse contains ' sign and space on the folder name or space on the file name.

here is the error on folder name

Unrecognized argument: 'Files\1.epub'

here is the error when the file name contains '

Unrecognized argument: 'the'

this is my code

String a = System.getProperty("user.dir") + "\\epubcheck-4.0.1\\" + "epubcheck.jar";
    Process p = Runtime.getRuntime().exec("java -jar" + " " + a + " " + selectedFile.getAbsolutePath());

here is how to run the epubchecker

java -jar epubcheck.jar file.epub

but when i run it on command prompt manually it didn't give me an error

Upvotes: 0

Views: 147

Answers (2)

Stephen C
Stephen C

Reputation: 719426

Adding quotes to the command string DOES NOT WORK.

The javadoc for exec(String, ...) says this:

More precisely, the command string is broken into tokens using a StringTokenizer created by the call new StringTokenizer(command) with no further modification of the character categories. The tokens produced by the tokenizer are then placed in the new string array cmdarray, in the same order.

If you then look at the javadoc for StringTokenizer, it says:

The StringTokenizer methods do not distinguish among identifiers, numbers, and quoted strings, nor do they recognize and skip comments.

and

The tokenizer [produced by new StringTokeniser(string)] uses the default delimiter set, which is " \t\n\r\f".

In other words, exec will split the command string into arguments, ignoring any quoting.

Any quotes (or double-backslash escapes) will simply be treated as notmal characters. For example:

    exec("java -jar \"C:/Users/My User Name/foo.jar\"");

will attempt to look for a JAR file called "C:/Users/My. Yes ... there is a leading quote at the start of the pathname.

You can avoid this problem by doing the argument yourself; e.g.

    exec(new String[]{"java",
                      "-jar",
                      "C:/Users/My User Name/foo.jar"});

Notice there are no added quotes.


It is also possible to use a shell to deal with quoting if (for some reason) your application is provided with an already-quoted pathname. For example (Linux / Unix / Mac OSX)

    exec(new String[]{"bash", 
                      "-c",
                      "java -jar \"/home/me/silly dir/foo.jar\""});

Upvotes: 1

Raffaele
Raffaele

Reputation: 20885

You should quote the tokens that make up your command line. Use the .exec(String[]) version

Runtime.getRuntime().exec(new String[]{"java"
     , "-jar"
     , a
     , selectedFile.getAbsolutePath()});

Upvotes: 4

Related Questions