Pass Batch variable as parameter to Java class using command line [duplicate] - java

This question already has answers here:
How do I pass parameters to a jar file at the time of execution?
(5 answers)
Closed 4 years ago.
How can we pass a batch variable as parameter to a Java class main method using command line? I want to pass the contents of a text file as an argument to a Java class using command line. for eg : Java -jar TestJar.jar %BATCH_VAR%
I have tried the below code and it doesnt seem to work :
echo "starting"
echo off
set keyvalue=^&Type TestDoc.txt
echo %keyvalue% /// This is printing the right value.
pause
java -jar ErrorUpdate.jar "%keyvalue%" //// This does not pass anything to the Java class :(
pause

I suspect that you may have a misconception about what value is stored in your variable. So let me clarify exactly what is going on in your batch file.
set keyvalue=^&Type TestDoc.txt
echo %keyvalue% /// This is printing the right value.
That is not printing the right value. What you have done is assigned the value &Type TestDoc.txt to the variable. When you then type echo %keyvalue%, this line gets expanded to the following line:
echo &Type TestDoc.txt
This is actually two separate commands. The first, echo, simply queries if the echo setting is currently on or off. The second command, Type TestDoc.txt, is then executed.
At no point does the variable keyvalue ever contain the contents of the file.
So when you have this line in your batch:
java -jar ErrorUpdate.jar "%keyvalue%"
It gets expanded to:
java -jar ErrorUpdate.jar "&Type TestDoc.txt"
This time, the & is enclosed in quotes, so it does not act as a statement separator, but instead is passed to your java class's main method. Your main method just sees the string "&Type TestDoc.txt" passed in as args[0].
If you want the java application to receive the full contents of the file, you need to make your java application read the contents itself.

Related

Java: Making an Optional Command Line Argument

I am working on a program that is supposed to take one required command line argument and one optional command line argument. The first argument is the name of an output file where data will be written to, and the second is a number that will be used to calculate the data to be written to the output file. If the user does not enter a number, then it should just use a default value to calculate the data. For example, if the user entered command line arguments "Foo.csv 1024" the program would use 1024 to calculate the data and write it to Foo.csv, but if the user only used the command line argument "Foo.csv" then the program would use a default value of 2048 to calculate the data and write it to Foo.csv. I am creating/running this program using the Intellij IDE. How would I do this? Any advice/suggestions would be much appreciated.
Your program seems to be simple, so the solution is also simple for this particular case. You can test how many arguments were passed to the program checking the argument args of your main function:
public static void main(String[] args){...}
args is an array that contains the arguments passed to your program. So if your program is called prog and you run it with prog Foo.csv 1024, then args will have:
args[0] = "Foo.csv";
args[1] = "1024";
With this, you know which arguments were passed to your program and by doing args.length, you can know how many they were. For the example above, args.length=2 If the user didn't indicate the last argument ("1024"), then you would have args.length=1 with the following in args:
args[0] = "Foo.csv";
So your program would be something like:
public static void main(String[] args){
//The default value you want
int number = 2048
if(args.length==2){
number = Integer.parseInt(args[1]);
}
//'number' will have the number the user specified or the default value (2048) if the user didn't specify a number
}
To supply arguments to your program you must run it on a console or some kind of terminal. Using IntelliJ (or any other IDE) it's also possible to run the program with arguments, but you specify those in the Run Settings.
If you want a more complex treatment of arguments, usually what you want is done by argument parsers. These are usually libraries that take you argv and help you reading arguments to your program. Among other things, these libraries usually support optional arguments, arguments supplied via flags, type checking of arguments, creating automatic help pages for your commands etc. Consider using an argument parser if your argument requirements are more complex or if you just want to give a professional touch to your program :)
For java i found this particular library: http://www.martiansoftware.com/jsap/doc/

how to pass null values as arguments from java to python

I have a java method that passes some arguments to a python file. I am passing the the arguments this way :
String name=null; //can be null or some value in some cases.
....
String[] cmd = {
"python",
"C:/Python34/myscript.py",
name,
username,
pwd};
Process p=Runtime.getRuntime().exec(cmd);
the variable name would be null in some execution and it might not but when it becomes null i am getting java.lang.NullPointerException.
My python file myscript.py will run with null values if i am running it from command prompt but i am not able to from java.
How can i pass null value without the exception. Can you help me with this?
Since python and java are different processes you are communicating between using system calls, you cannot convert Java null to the command line.
(What you call null in Python is actually None)
What you can do is: pass empty string ("" not null) to the python program, and the python program can interpret empty strings and convert them to None.
Or decide a convention: if "<NULL>" string is passed from java then assume None from python side when parsing the args.
Other solutions like Jython would maybe allow this because they do no involve system calls.
Instead of passing them as null, do a NullPointer check and pass in empty strings.
name = name == null ? "" : name;
That way your python script will just need to check for empty strings instead of nulls. And you can check for both by a simple if check. Something like below will work.
if not name:
# this will check for both None and "" empty string
print "name was not passed"

How can a script take different types of command line arguments and feed it to a java program?

So I need to make a java program that represents a bank tiller. However, I need to use an executable script that will feed the command line arguments to the java program. Unfortunately, there are multiple types of commands I can do that would need to call the java program.
Since there are different types of command options (start, buy, and change, I do not know how I could go about feeding the right argument information to the java program. Any assistance would be greatly appreciated.
Unless I'm missing something, you could use $# to pass the script's arguments to your Java program. For example,
#!/usr/bin/env bash
export CLASSPATH="$HOME/src/java/"
java com.example.MyTeller "$#"
Pass the script arguments to your Java program:
java programName "$#"
Here is a sample:
public class PrintArgs {
public static void main (String[] args) {
for (int x=0; x<args.length; x++) {
System.out.println(arg[x]);
}
}
}
Call it like this:
java PrintArgs start 80 = 10 2 2 2
The script I am not that sure about, but I you can look it up. Google shell scripts arguments.
Take a look at the Apache CLI stuff. Specifically the POSIX parser (http://www.javaworld.com/article/2072482/command-line-parsing-with-apache-commons-cli.html)
It will enable you to specify POSIX style command line arguments (--buy {value} --sell {value})...

Set System.setOut(); to Command Prompt [duplicate]

This question already has answers here:
How to execute cmd commands via Java
(11 answers)
Closed 9 years ago.
I want to set output stream to the Command prompt like this:
Process p = Runtime.getRuntime()
.exec("C:\\Windows\\System32\\cmd.exe /c start cls");
System.setOut(new PrintStream(p.getOutputStream()));
but it is not working, why ?
By default, PrintStreams will not flush contents written to them automatically. This means that data you write to it will not be immediately sent to the stream it wraps around. However, if you construct the PrintStream using new PrintStream(p.getOutputStream(), true), it will automatically flush when any of the println methods are invoked, a byte array is written or a newline is written. This way, anything you write to it will be immediately accessible to the process.
See http://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html

What is exactly args and how do i used it? [duplicate]

This question already has answers here:
What is the "String args[]" parameter in the main method?
(18 answers)
Closed 9 years ago.
I am a new programer and I'm just starting to learn the basics of Java and I'm trying to understand what exactly "args" stands for in "public static void main(String[] args)".
I found that's it's connected to command line arguments, which I don't understand. I would like to know what "args" means.
Thank you.
When you run a Java program, it usually looks like this:
java MyProgram
However, you also have the option of including command-line arguments. For example, if your program adds two numbers, you could set it up to take input like this:
java MyProgram 12 47
In this case, arr would equal ["12", "47"]. Having input work in this way is useful because it makes it easier to automate the running of your program through batch files or the like.
args is an arbitrary name for command line arguments. Running a java class file from the command line will pass an array of Strings to the main() function. If you want to handle extra arguments, you can check for keywords at certain indices of args and perform extra functions based on them.

Categories