- Interacting with Java Jar through Command Line
- 2 Answers 2
- Run a Java Application from the Command Line
- Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
- > CHECK OUT THE COURSE
- 1. Overview
- Further reading:
- Run JUnit Test Cases From the Command Line
- Command-Line Arguments in Java
- Command-Line Arguments in Spring Boot
- 2. Create a JAR Application
- 3. Java Command-Line Arguments
- 4. Run an Executable JAR with Arguments
- 5. Run a Nonexecutable JAR with Arguments
- 6. Conclusion
- How can I give parameter values while executing a jar?
- 3 Answers 3
Interacting with Java Jar through Command Line
What are some ways to interact with a jar post creation in the command line? I know you can pass parameters when it’s created (e.g. java -jar foo.jar foo bar) but this isn’t what I want. Example of what I would like to happen
// Someway to interact with the above jar e.g. Call a method
@GregWringle why? Why focus on methods? This exposes far too much of the internals of the application to the end user. Look into, for example, JMX. Or you could go the whole way and use an HTTP server and REST (for another example).
2 Answers 2
A typical method to interact with a jar file is to specify the main class to be called, and then read the arguments from command line.
public static void main(final String[] args) < // evaluate command line arguments here System.out.println("number of arguments=" + args.length); System.out.println("arg1" + args[0]); >
java.exe -cp myjar.jar com.mycompany.Myclass arg1 arg2 arg3
where MyClass contains the main method.
public static void main(String args[]) < int n=args.length; // number of arguments String arg1=args[0]; // param 1 // then param2, . >
Interacting during the program:
BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in)); String line=buffer.readLine(); System.out.println("LINE:"+line);
If you want to run some task, and in the same time, get some user input, you have to launche yours tasks with a thread: see this for example: Java — creating a new thread
Run a Java Application from the Command Line
Repeatedly, code that works in dev breaks down in production. Java performance issues are difficult to track down or predict.
Simply put, Digma provides immediate code feedback. As an IDE plugin, it identifies issues with your code as it is currently running in test and prod.
The feedback is available from the minute you are writing it.
Imagine being alerted to any regression or code smell as you’re running and debugging locally. Also, identifying weak spots that need attending to, based on integration testing results.
Of course, Digma is free for developers.
As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
> CHECK OUT THE COURSE
1. Overview
Typically, every meaningful application includes one or more JAR files as dependencies. But there are times a JAR file itself represents a standalone application or a web application.
Here we’ll focus on the standalone application scenario. From now on, we’ll refer to it as a JAR application.
In this tutorial, we’ll first learn how to create a JAR application. Later, we’ll learn how to run a JAR application with or without command-line arguments.
Further reading:
Run JUnit Test Cases From the Command Line
Command-Line Arguments in Java
Command-Line Arguments in Spring Boot
2. Create a JAR Application
A JAR file can contain one or more main classes. Each main class is the entry point of an application. So, a JAR file can theoretically contain more than one application, but it has to contain at least one main class to be able to run.
A JAR file can have one entry point set in its manifest file. In this case, the JAR file is an executable JAR. The main class has to be included in that JAR file.
First, let’s see a quick example of how to compile our classes and create an executable JAR with a manifest file:
$ javac com/baeldung/jarArguments/*.java $ jar cfm JarExample.jar ../resources/example_manifest.txt com/baeldung/jarArguments/*.class
A nonexecutable JAR is simply a JAR file that doesn’t have a Main-Class defined in the manifest file. As we’ll see later, we can still run a main class that’s contained in the JAR file itself.
Here’s how we would create a nonexecutable JAR without a manifest file:
$ jar cf JarExample2.jar com/baeldung/jarArguments/*.class
3. Java Command-Line Arguments
Just like any application, a JAR application accepts any number of arguments, including zero arguments. It all depends on the application’s need.
This allows the user to specify configuration information when the application is launched.
As a result, the application can avoid hard-coded values, and it still can handle many different use cases.
An argument can contain any alphanumeric characters, unicode characters and possibly some special characters allowed by the shell, for example, @.
Arguments are separated by one or more spaces. If an argument needs to contain spaces, the spaces have to be enclosed between quotes. Either single quotes or double quotes work fine.
Usually, for a typical Java application, when invoking the application, the user enters command-line arguments after the name of the class.
However, that’s not always the case for JAR applications.
As we discussed, the entry point of a Java main class is the main method. The arguments are all Strings and are passed to the main method as a String array.
That said, inside the application, we can convert any element of the String array to other data types, such as char, int, double, their wrapper classes or other appropriate types.
4. Run an Executable JAR with Arguments
Let’s see the basic syntax for running an executable JAR file with arguments:
java -jar jar-file-name [args …]
The executable JAR created earlier is a simple application that just prints out the arguments passed in. We can run it with any number of arguments.
Here’s an example with two arguments:
We’ll see this output in the console:
So, when invoking an executable JAR, we don’t need to specify the main class name on the command line. We simply add our arguments after the JAR file name. If we do provide a class name after the executable JAR file name, it simply becomes the first argument to the actual main class.
Most times, a JAR application is an executable JAR. An executable JAR can have a maximum of one main class defined in the manifest file.
Consequently, other applications in the same executable JAR file can’t be set in the manifest file, but we can still run them from the command line just like we would for a nonexecutable JAR. We’ll see exactly how in the next section.
5. Run a Nonexecutable JAR with Arguments
To run an application in a nonexecutable JAR file, we have to use -cp option instead of -jar.
We’ll use the -cp option (short for classpath) to specify the JAR file that contains the class file we want to execute:
java -cp jar-file-name main-class-name [args …]
As we can see, in this case, we’ll have to include the main class name in the command line, followed by arguments.
The nonexecutable JAR created earlier contains the same simple application. We can run it with any (including zero) arguments.
Here’s an example with two arguments:
And, just like we saw above, we’ll see this output:
6. Conclusion
In this article, we learned two ways of running a JAR application on the command line with or without arguments.
We also demonstrated that an argument could contain spaces and special characters (when allowed by the shell).
As always, the code for the examples is available over on GitHub.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
How can I give parameter values while executing a jar?
I’ve already generated the jar for my project. But ‘m quite unsure of how to pass values to the jar while executing it through CMD . I’m already aware of how to pass parameters to the jar, but then unclear how can I pass values to the above two Strings .
3 Answers 3
Inside you main() method, you need to declare your 2 variables :
public static void main(String[] args)
And so, pass year as the first argument and month as the second 😉
To avoid reinventing the wheel and bugs, you should consider using a library like Apache Commons CLI which will parse your command properly for you.
public static void main(final String[] args) < Options options = new Options(); options.addOption( Option.builder("y") .required(true) .hasArg(true) .desc("The year") .longOpt("year") .build() ); options.addOption( Option.builder("m") .required(true) .desc("The months") .numberOfArgs(Option.UNLIMITED_VALUES) .longOpt("month") .build() ); CommandLineParser parser = new DefaultParser(); CommandLine cmd; try < cmd = parser.parse(options, args); >catch (ParseException e) < System.err.println( "Could not parse the command due to: " + e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "java", options ); return; >String year = cmd.getOptionValue("y"); String[] months = cmd.getOptionValues("m"); // Rest of your code here >
You will then be able to provide your arguments using -y or —year in case of the year and using -m or —month in case of the months. The usage will also be printed in case of a parsing error.
If you want to do it manually (assuming that you have the year first followed by the months), your code will then be:
public static void main(final String[] args)
But we should add more tests to ensure that the total amount of arguments is correct and the arguments are valid which is the reason why I propose to use a library instead.