Packaging a jar with preconfigured command line arguments - java

I am wondering if there's a way to create a jar that includes some command line arguments in it, the arguments that are usually passed in the command line when one tries to start up the jar (these parameters are then passed on to the main function). Basically instead of starting my app with
java -jar myapp.jar "arg1" "arg2", I want to start my app with
java -jar myapp.jar
and have "arg1" and "arg2" passed to the main function.
The reason behind this is that I want to deploy this to different environments, and I want my jar to contain different parameters according to the environment it's being deployed at.
Maybe there's another way to achieve similar results ??
Cheers.
PS: Looking for a maven solution.
Edit: I'll add a complete example to make this a bit more clear:
Let's say I have 2 environments: "Production" and "Test". I want to run the jar in the same way no matter in what environment I deploy it. So I always want to run it with:
java -jar myapp.jar
But! In order for my 2 environments to run ok, I need the Production environment jar to start it's main method with an argument "prod" and I need the Test environment jar to start it's main method with an argument "test".

If I correctly understood your problem, in your main() you could define a simple logic to handle the case where you do not specify any input parameter; the logic could retrieve the desired values according to the correct platform/env.
As an example:
public class Test01
{
public static void main(String... aaa)
{
// Check input
if(aaa.length == 0) {
/* Insert logic to retrieve the value you want, depending on the platform/environment.
* A trivial example could be: */
aaa = new String[2];
aaa[0] = "First value";
aaa[1] = "Second value";
}
// Processing, e.g. print the 2 input values
System.out.println(aaa[0] + ", " + aaa[1]);
}
}
Fyi, I created a runnable jar using eclipse, and start the application by either
java -jar Test01.jar
or
java -jar Test01.jar arg1 arg2
Hope this helps!

One solution is to change main(String[] args) to get values from env var if they are not present in the passed arguments.
String user;
String password;
if(args.length < 2)
{
user = System.getenv("appUser");
password = System.getenv("appPassword");
} else {
user = args[0];
password = args[1];
}
You can also create another class with a main function that will call the real one.
public class CallerMyApp{
public void main(String[] args) {
String[] realArgs = {System.getenv("appUser"), System.getenv("appPassword")};
MyApp.main(realArgs);
}
}
Then to execute its something like
java -cp myapp.jar CallerMyApp

Related

Trying to understand how to create a jar file that opens terminal and takes in a argument

I finished creating a program but I was told that my program
must be a Java application that takes as a command line argument the name of the file."
I understand I can use the jar command in terminal but I don't undestand how you open the terminal and take a file name as a argument. I was wondering if someone could explain what code is required to do this.
Thanks alot.
I tried creating a basic jar file in terminal with the line "jar cvf findOptimalTransport.jar ." but the jar file does not open, I think its because the current implementation takes the users input with a scannar in the code and prints via the terminal. However, this wont work because a terminal window is not opened with this command.
It doesn't have to be a jar file. Command line arguments can be entered from the command line, when you run your application.
Let me give you an example, about how this works. Let's say you have the below simple Java application:
public class MyApplication{
public static void main(String[] arguments){
System.out.println("Hello World!");
}
}
That public static void main() is a method; and more specifically the main method of your application which is what is executed when compiled and ran.
To compile and then run it, you type in the command line/terminal:
javac MyApplication.java //this will compile it
java MyApplication //this will run the main method of MyApplication
But what is that parameter in the main method? What is String[] arguments ?
When you run your program, whatever you type after the application name is an argument, of type String and it is stored in the String array String[] arguments (or most commonly String[] args).
What this means, is that, if you execute your application like this:
java MyApplication some_file.txt // Run application with one arg.
You can access that argument like so:
public class MyApplication{
public static void main(String[] arguments){
System.out.println("Hello World!");
System.out.println("You entered: " + arguments[0]);
}
}
Output:
Hello World!
You entered: some_file.txt
Note: To run a jar file, you need to navigate to the folder that the jar file is in and from the command line you can run it by typing:
java -jar <jarname>.jar

How can I handle spaces in arguments?

My app launches and loads the file if I do: myApp /file:c:\nospaces.asd from cmd but if I do myApp /file:c:\with spaces.asd it won't work because the program receives two arguments: myApp /file:c:\with and spaces.asd.
I know that I can do myApp "/file:c:\with spaces.asd" and it'll work like that from cmd. However this isn't a good solution because if I double click the .asd file (custom extension) (and select launch with my app) then main won't be getting the arguments as one line but as two arguments.
How can I go about fixing this issue so that my main will receive only one argument when double clicking the file?
You could join the arguments together if the file is not found. Something like this:
public static void main(String[] args) {
String fileName = joinArgumentsToValidFileName(args);
}
public static String joinArgumentsToValidFileName(String[] args) {
if(args.length == 0) {
return "";
}
String fileName = args[0];
int index = 1;
while(!new File(fileName).exists() && index < args.length) {
fileName += " " + args[index];
index++;
}
return fileName;
}
This assumes that the first argument (or the arguments) must be the file name. Any additional agruments could be evaluated by remembering the offset index somehow (not included in the code above).
But note: This is a not standard behavior of passing arguments to an application and could lead to cunfusion. So if you find a way to pass a "" wrapped file name argument, don't do this!
Double clicking to launch java would be affected by whats registered in windows related to the same i.e windows registry for jar-file launch command.
These are some similar questions asked on SO you can take a look at:
Running JAR file on Windows
java can run jar from cmd but not by double clicking
They mention the useful part which is ensuring you have the wildcard behind the executable in the registry c:\...\javaw.exe" -jar "%1" %

Split rule of args in main function in Java?

Here is a strange problem I ran into:
I create a single program to print all the received args, Here is the code:
public class Test {
public static void main(String[] args) {
for (int i = 0; i < args.length; i ++) {
System.out.println(args[i]);
}
}
}
Then I built a jar file of it and ran the following command:
java -jar test.jar test&1
However, it didn't print "test&1" as expected. The result of it is:
test
'1'is not recognized as an internal or external command,operable program or batch file.
So my question is: what is the seperation of args? If I really need to receive "test&1", what should I do?
Thanks!
It's nothing to do with Java. The & character is special to the Windows shell (I can tell it's Windows from the error message): It separates two commands on one line, so what you're doing is telling the shell to run java -jar test.jar test and then run 1. If you want to pass test&1 to Java, you'll have to put it in quotes:
java -jar test.jar "test&1"
The & is also special on *nix shells (but in a different way, it runs the command in a sub-shell). There, you could use quotes as above, or put an \ before the & instead. But not on Windows.

How to read and write text files from the main in java

The static method main, which receives an array of strings. The array should have two elements: the path where the files are located (at index 0), and the name of the files to process (at index 1). For example, if the name was “Walmart” then the program should use “Walmart.cmd” (from which it will read commands) and “Walmart.pro” (from which it will read/write products).
I don't want anyone to write the code for me because this is something I need to learn. However I've been reading this through and the wording is confusing. If someone could help me understand what it wants from me through pseudo-code or an algorithm it would be greatly appreciated.
Where I'm confused is how to initialize arg[0] and arg[1] and exactly
what they are being initialized to.
The main method's String array input argument consists of whatever String arguments you pass to the program's main method when you run the program. For example, here is a simple program that loops over args and prints a nice message with each argument's index and value on a separate line:
package com.example;
public class MainExample {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.printf("args[%d]=%s\n", i, args[i]);
}
}
}
Once you've compiled the program, you can run it on the command-line and pass it some arguments:
java -cp . com.example.MainExample eh? be sea 1 2 3 "multiple words"
Output:
args[0]=eh?
args[1]=be
args[2]=sea
args[3]=1
args[4]=2
args[5]=3
args[6]=multiple words
So lets explain to you
Create a class Inventory : if you don't know how to create a class google it just as is
The static method main: Every executable class in java (at least from the console) has the main method you should google java main method and propably in the same place you find it you will see the default arguments that it receives
When you learn about the default arguments of method main you will undertand about the 'args' that has to be on it
You will have t study the class String google it "java String class"
You will have to study the class File google it "java File class"
At the end everything else would be just logic and I beleave you have learned some at this point.
public class Inventory { // class inventory
public static void main(String[] args) // main method
{
if(args.length==2){ // check if args contains two elements
String filePath = args[0];
String fileName = args[1];
filePath+= System.getProperty("file.separator")+fileName;
File fileCMD = new File(filePath+".cmd");
//fileCMD.createNewFile();
File filePRO =new File(filePath+".pro");
//filePRO.createNewFile();
}
else {
//write the code to print the message Usage: java Inventory Incorrect number of parameters for a while and exit the program.
}
}
This is what I've understood. Basically you have to write a program to create two files, one called fileName.cmd and the other fileName.pro. You have to construct the path of the files using the arguments (input parameters of the main method) and system's file separator. If the arguments don't have two elements you have to print the 'invalid' message. That's it.
Where I'm confused is how to initialize arg[0] and arg[1] and exactly
what they are being initialized to.
You have to use command line to pass the arguments and launch the program , something like the following code in cmd or terminal:
java inventory thePath theFileName
That's how it get initialized.

Passing on command line arguments to runnable JAR [duplicate]

This question already has answers here:
How do I pass parameters to a jar file at the time of execution?
(5 answers)
Closed 5 years ago.
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.
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
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.
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");
....
}
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.

Categories

Resources