Passing on command line arguments to runnable JAR

126,488

Solution 1

Why not ?

Just modify your Main-Class to receive arguments and act upon the argument.

public class wiki2txt {

    public static void main(String[] args) {

          String fileName = args[0];

          // Use FileInputStream, BufferedReader etc here.

    }
}

Specify the full path in the commandline.

java -jar wiki2txt /home/bla/enwiki-....xml

Solution 2

You can also set a Java property, i.e. environment variable, on the command line and easily use it anywhere in your code.

The command line would be done this way:

c:/> java -jar -Dmyvar=enwiki-20111007-pages-articles.xml wiki2txt

and the java code accesses the value like this:

String context = System.getProperty("myvar"); 

See this question about argument passing in Java.

Solution 3

You can pass program arguments on the command line and get them in your Java app like this:

public static void main(String[] args) {
  String pathToXml = args[0];
....
}

Alternatively you pass a system property by changing the command line to:

java -Dpath-to-xml=enwiki-20111007-pages-articles.xml -jar wiki2txt

and your main class to:

public static void main(String[] args) {
  String pathToXml = System.getProperty("path-to-xml");
....
}
Share:
126,488
Jason
Author by

Jason

Full stack Python & Java web dev in sunny/snowy Maine. Other interests include geospatial data and puzzles

Updated on June 27, 2020

Comments

  • Jason
    Jason almost 4 years

    I built a runnable JAR from an Eclipse project that processes a given XML file and extracts the plain text. However, this version requires that the file be hard-coded in the code.

    Is there a way to do something like this

    java -jar wiki2txt enwiki-20111007-pages-articles.xml
    

    and have the jar execute on the xml file?

    I've done some looking around, and all the examples given have to do with compiling the JAR on the command line, and none deal with passing in arguments.