Passing on command line arguments to runnable JAR

2019-01-14 01:45发布

This question already has an answer here:

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.

4条回答
走好不送
2楼-- · 2019-01-14 02:20

When you run your application this way, the java excecutable read the MANIFEST inside your jar and find the main class you defined. In this class you have a static method called main. In this method you may use the command line arguments.

查看更多
等我变得足够好
3楼-- · 2019-01-14 02:23

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");
....
}
查看更多
聊天终结者
4楼-- · 2019-01-14 02:25

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
查看更多
够拽才男人
5楼-- · 2019-01-14 02:25

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.

查看更多
登录 后发表回答