package commandLine;
public class commandLine {
public static void main(String[] args) {
System.out.println("There are " +args.length+ " Command-line Arguments");
System.out.println("They are: ");
for(int i=0;i<args.length;i++){
System.out.println("arg["+i+"]: "+args[i]);
}
}
}
I wanted to check the length of my command-line arguments and loop through them to display the array of command lines. However, it says my command line arguments are 0? How can this be?
Official Java tutorial about command-line arguments.
Command-Line Arguments
A Java application can accept any number of arguments from the command
line. This allows the user to specify configuration information when
the application is launched.
The user enters command-line arguments when invoking the application
and specifies them after the name of the class to be run. For example,
suppose a Java application called Sort sorts lines in a file. To sort
the data in a file named friends.txt, a user would enter:
java Sort friends.txt
When an application is launched, the runtime
system passes the command-line arguments to the application's main
method via an array of Strings. In the previous example, the
command-line arguments passed to the Sort application in an array that
contains a single String: "friends.txt".
Echoing Command-Line Arguments
The Echo example displays each of its command-line arguments on a line
by itself:
public class Echo {
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
}
The following example shows how a user might run Echo. User input is
in italics.
java Echo Drink Hot Java
Drink
Hot
Java
Note that the application
displays each word — Drink, Hot, and Java — on a line by itself. This
is because the space character separates command-line arguments. To
have Drink, Hot, and Java interpreted as a single argument, the user
would join them by enclosing them within quotation marks.
java Echo "Drink Hot Java" Drink Hot Java
If you are using IDE (Eclipse or etc.) you have to specify command-line arguments via some kind of run configuration. For example for Eclipse:
In have the command line is essentially of the form
java [vm options] class/jar [arguments]
Only these final arguments are given to you in the array. This is unlike a standard C program where you receive the command name also.
Related
I'm getting different results testing a simple java class on Windows cmd and wsl (ubuntu).
The java class:
public class PrintArgs {
public static void main(String[] args) {
System.out.println("Printing some arguments in this code: ");
// Loop through arguments passed and print them to standard output
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + (i + 1) + ": " + args[i]);
}
}
}
I use this test arguments:
java PrintArgs.java Test "Testing TestThis" 'Some arguments' ´More Arguments´
In cmd, the single quote doesn't group the arguments:
cmd results and java version
but in ubuntu, it does:
wsl results and java version
Any idea why this is happening?
The Java process will already get an array of strings as the argument (in anything C-based it's more like a **char, but that's close enough). It doesn't even see the quotes that group a single argument together, because those will already have been interpreted by the shell.
The shell (probably Bash in WSL and cmd.exe in the command window) is responsible for taking the single continuous string of what the user entered and splitting it into arguments (and expanding wildcards, where applicable, but that doesn't happen in this case).
Now Bash and cmd.exe have different rule about how quoting works, so they split the single string differently.
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
Is there a way to read data from the command prompt? I have a java program that relies on 4 input variables from an outside source. These variables are returned to the command prompt after I run a javascript program but i need a way to pass these variables from the command prompt into my java program, any help would be greatly appreciated!
While executing java program pass the parameters and all the parameters should be separated by space.
java programName parameter1 parameter2 parameter3 parameter4
This parameters would be available in your main method argument
public static void main(String[] args){
//This args array would be containing all four values, i.e. its length would be 4 and you easily iterate values.
for(int i=0; i<args.length; i++){
System.out.println("Argument " + i + " is " + args[i]);
}
Follow the link:
Command-Line Arguments - The Java™ Tutorials : https://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html
shared by #BackSlash.
It has all the content which would help you to clear all your doubts.
The content from the link is quoted below:
Displaying Command-Line Arguments passed by user from command-line to a Java program
The following example displays each of its command-line arguments on a
line by itself:
public class DisplayCommandLineParameters {
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
}
To compile the program: From the Command Prompt, navigate to the directory containing your .java file, say C:\test, by typing the cd
command below.
C:\Users\username>cd c:\test
C:\test>
Assuming the file, say DisplayCommandLineParameters.java, is in the
current working directory, type the javac command below to compile it.
C:\test>javac DisplayCommandLineParameters.java
C:\test>
If everything went well, you should see no error messages.
To run the program: The following example shows how a user might run the class.
C:\test>java DisplayCommandLineParameters Hello Java World
Output:
Hello
Java
World
Note that the application displays each word — Hello, Java and World —
on a line by itself. This is because the space character separates
command-line arguments.
To have Hello, Java and World interpreted as a single argument, the
user would join them by enclosing them within quotation marks.
C:\test>java DisplayCommandLineParameters "Hello Java World"
Output: Hello Java World
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.
I would like to know if it is possible to get from code the command used to launch a java program.
E.g. if I launch a java program with:
java -cp lib1:lib2:... -jar mylib.jar com.foo.Bar
I would like to get the exact string (jvm parameters included).
Is it possible?
Comment on the bounty and the question
Thank you all for your responses. Unfortunately, I did not get the answer I was initally looking for. I was hoping there was some portable solution to get the complete java command from within the program itself (including classpath etc.). As it seems there are no portable solution and since I am using Linux I am using the responses of agodinhost and Luigi R. Viggiano to solve my problem. However I give the bounty to rahulroc for the most complete (portable) response. For the rest an upvote for all :)
The below mentioned code should show all JVM parameters, arguments passed to the main method as well as the main class name.
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.List;
public static void main(String[] args) {
RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
List<String> jvmArgs = bean.getInputArguments();
for (int i = 0; i < jvmArgs.size(); i++) {
System.out.println( jvmArgs.get( i ) );
}
System.out.println(" -classpath " + System.getProperty("java.class.path"));
// print the non-JVM command line arguments
// print name of the main class with its arguments, like org.ClassName param1 param2
System.out.println(" " + System.getProperty("sun.java.command"));
}
javadoc for getInputArguments
Returns the input arguments passed to the Java virtual machine which
does not include the arguments to the main method. This method returns
an empty list if there is no input argument to the Java virtual
machine.
Some Java virtual machine implementations may take input arguments
from multiple different sources: for examples, arguments passed from
the application that launches the Java virtual machine such as the
'java' command, environment variables, configuration files, etc.
Typically, not all command-line options to the 'java' command are
passed to the Java virtual machine. Thus, the returned input arguments
may not include all command-line options.
You can also take a look at : jps
It's a Java program that is able to get the full command line for all
Java processes, including full class name of main class and JVM
options.
You can find a good summary of various JVM tools, including
Java Application Launcher links to :
ManagementFactory.getRuntimeMXBean() - Returns the managed bean for the runtime system of the Java virtual machine.
getInputArguments() javadoc
determine if JVM is running in debug mode
You can use this to retrieve the VM parameters :
public static void main(String args[]) {
List<String> inputArguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
System.out.println("input arguments = " + inputArguments);
}
However it won't give you all the command line (only gives the JVM arguments, no main class nor parameters). Sample output:
input arguments = [-Dfile.encoding=UTF-8, -XX:-UseTLAB, -Xms2000m, -Xmx2000m, -XX:+PrintCompilation, -XX:+PrintGC]
It only works on Sun Oracle JVM: System.getProperty("sun.java.command")
Additionally, you can have a look at JavaSysMon, it can report command line of active processes. To check which is the current JVM Process check here: How can a Java program get its own process ID?
in a linux machine would be easier to run:
ps -ef | grep java
this command will list all java programs running with it's used parameters.
Not sure about what can be used in a windows environment.
In the task manager on Win2003 you can enable the display of a column that displays the command like it does on linux. Or, you can do it from the command line like so:
wmic.exe PROCESS where "name like '%java%'" get Processid,Caption,Commandline