How to specify a text file in the command line - java

I am trying to create a program that reads from a text file. I use cmd and type in javac fileName.java to compile, then java -cp . fileName to run it. However, I want to run the program by writing java fileName textInput.txt. I have already created the program; but I have to specify the name of the text file in the code.
I was told that args[0] should be the name of the text file, but I am not sure how to implement this.
I have not posted my code, but tell me if I need to.

If you have your class as below
public class YourClass {
public static void main(String[] args) {
String fileName = args[0]; // would contain "textInput.txt"
// work with fileName
}
}
run your program as java YourClass textInput.txt.
The String array args contains any arguments you pass when you run the java command. It can be anything, not restricted to file names. As Bailey S puts it, these arguments are tokenized based on the tokenization of your shell. The index starts at 0.
java YourClass arg1 arg2 arg3
^ ^ ^
index: 0 1 2

String filePath = args[0];
// Do whatever with the file path

The main method of any Java program receive an array of String values which are the arguments passed via the command line:
java javaClass.class arg0 arg1 arg2
And here is how you catch from the code:
public static void main(String[] args)
{
System.out.println(args[0]); // prints arg0
System.out.println(args[1]); // prints arg1
System.out.println(args[2]); // prints arg2
}
It is better to check the number of arguments passed before using them:
if(args.length < 0) System.out.println("No arguments are passed!");

class fileName {
public static void main(String[] args) {
String filePath = args[0];
//but check if args[0] exist.
}
}

Related

How would you pass two arguments to the command line?

String input = "";
if (args.length>0)
{
input=args[0];
}
I was able to use this method to write from the command line an pass one argument, but I'm unsure how to pass a second argument. Sorry for brief description unsure what else to say?
Assuming you have a standard main() method args will be an array so you can simply access the next index to get the next argument value:
public static void main(String[] args) {
String first = args[0];
String second = args[1];
...
}
This works when you call java with the arguments separated by a space
java MyClass arg1 arg2

How to pass array of strings to a Java program?

In:
public static void main (String [ ] args)
How to set the value parameter variable args of the main method as an array of String?
The args are optional command line values.
java MyProgram --arg1 --arg2
could be accessed as
args[0] == "--arg1"
args[1] == "--arg2"
Value is passed as command line arguments.
For ex, you have this program(Cmd.java):
public class Cmd
{
public static void main(String agrs[])
{
System.out.println("Values are:"+args[0]+" and "+args[1]);
args[0]="New1";
args[1]="New2";
System.out.println("Modified values are:"+args[0]+" and "+args[1]);
}
}
Compile it like:
javac Cmd.java
Execute it like:
java Cmd Value1 Value2
Output will be:
Values are Vaue1 and Value2
Modified values are New1 and New1
Hope you got the point!
BONUS:
If you don't pass any values during execution the program will throw an ArrayIndexOutOfBoundsException.
You may want to handle that!
Read more about Command Line arguments at The Java tutorials (Oracle docs)!
When you execute your java program in command line you can provide arguments to the executable:
java MyClass arg0 arg1 arg2
In Java the word args contains the command-line arguments that are given in input to your program as an array of String Objects.
That is, if you run java AnExample a b, args will contain ["a", "b"].
So, if you want just to print out the contents of args, you can simply loop through them:
public class HelloWorld {
public static void main( String[] args ) {
for( int i=1; i < args.length; i++ ) {
System.out.println( args[i] );
}
}
}
For a deep explication of the Java args you can read this interesting presentation from Emory university.
You can set an array of Strings when you call the program.
java MyClass args0 args1 etc
If you are using Eclipse then this is done under Project->Run Configurations/Debug Configurations. Click the Arguments tab and enter your arguments in the Program arguments box.
The String args[] contains all the arguments you pass to a Java program when you start it with a command line.
Example command to launch a Java application:
java MyApp arg1 arg2
What we have done in the example above is we passed 2 arguments to our MyApp java application ("arg1" and "arg2").
You can now use them however you want.
yup..
just compile your code by
javac <class name> args0 args1 ..

What does (String[] arguments) mean? [duplicate]

This question already has answers here:
What is the "String args[]" parameter in the main method?
(18 answers)
Why does main method in Java always need arguments?
(8 answers)
Closed 9 years ago.
I added the following code to a new class I created in Java:
public static void main(String[] arguments) {
I understand what public, static and void mean, but what does (String[] arguments) mean?
Your main() method can take input parameters of type String if your program is run through a console like
java YourClass arg1 arg2
Now, within main() if you iterate the String [] like
for (arg : arguments)
System.out.println(arg);
it should print
arg1
arg2
Demo :
public class AddTwoNumbers {
public static void main(String[] args) {
if(args.length == 2) {
try {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.println("a + b = " + a + " + " + b + " = "+ (a + b));
} catch (NumberFormatException e) {
System.err.println("Invalid Input: Please enter numbers.");
}
} else {
System.err.println("Missing Input: Please enter TWO numbers.");
}
}
}
You can run this on your console as
java AddTwoNumbers 2 3
and it should print
a + b = 2 + 3 = 5
It literally means "an array, where every element inside of it is at least a String, which we will name arguments".
In the context of the rest of the line, the method main takes as input, "an array, where every element inside of it is at least a String, which we will name arguments"
Since this is the public static void main(String[] arguments) method call, there is a special "exception to the rule" of normal parameter passing. Methods that look like this are one of the very few times when your input is not defined in some other part of your program. Instead the Java Virtual Machine constructs the input into this method, from the command line arguments you gave the JVM.
It means that the function expects an array of strings.
String[] arguments is the array for run time argument to your java program. If required you can pass arguemnts to your java program like this:
java yourJavaMainClass args1 args2
In your java code you can use the arguments provided by simply iterating over this array.
arguments[0] // this should give you the args1
It's the array of parameters that you may pass to your program during the execution. Ex:
java YourClass param1 100 X
In your runtime, you'll have this array
System.out.println(args.length); //prints 3
System.out.println(args[0]); //prints param1
System.out.println(args[1]); //prints 100
System.out.println(args[2]); //prints X
These are the parameters that the main function expects.
String [] arguments is a java array of String objects. This means that the main function expects an array of Strings. This array of strings typically holds all command line parameter arguments passed in when the program is run from the command line.
From the command line
java className stringOne stringTwo
In the program
Note : means in .. So read this as for stringObject in arguments
for (stringObject : arguments) {
System.out.println(stringObject);
}
Or if you know the exact amount of Strings that will be in arguments is two then
System.out.println(arguments[0]);
System.out.println(arguments[1]);
Output->
stringOne
stringTwo
Hope this helps! Good luck learning Java
Run the program using command line and the input provided there gets stored in obj array. So if you run the class as java className a1 a2 then object array will have a1 and a2 as elements.
Or if you are using eclipse IDE the go to run/debug config and do as shown

What does "String[] args" contain in java?

When I run the following program:
public class Test
{
public static void main(String[] args)
{
System.out.println(args);
}
{
It prints: [Ljava.lang.String;#153c375
and when I run it again, it prints: [Ljava.lang.String;#1d1e730
it gives me different output each time
So, what does "[Ljava.lang.String;#153c375" mean?
Update: I just realized I never answered the question "What does “String[] args” contain in java?" :-) It's an array of the command-line arguments provided to the program, each argument being a String in the array.
And we now resume with our regularly-scheduled answer...
args is an array. To see individual command-line arguments, index into the array — args[0], args[1], etc.:
You can loop through the args like this:
public class Test
{
public static void main(String[] args)
{
int index;
for (index = 0; index < args.length; ++index)
{
System.out.println("args[" + index + "]: " + args[index]);
}
}
}
For java Test one two three, that will output:
args[0]: one
args[1]: two
args[2]: three
Or loop like this if you don't need the index:
public class Test
{
public static void main(String[] args)
{
for (String s : args)
{
System.out.println(s);
}
}
}
So, what does "[Ljava.lang.String;#153c375" mean?
That's Java's default toString return value for String[] (an array of String). See Object#toString. The [ means "array", the L means "class or interface", and java.lang.String is self-explanatory. That part comes from Class#getName(). The ;#153c375 is ;# followed by the hashCode of the array as a hex string. (I think the default implementation of hashCode for Object indicates where in memory the array is located, which is why it's different for different invocations of your program, but that's unspecified behavior and wouldn't be any use to you anyway.)
String[] args in main method is the String array of the command line arguments.
[Ljava.lang.String;#1d1e730 are the class name ([Ljava.lang.String is String[]) and the object's hashcode (#1d1e730);
if you want to print the actual values of the Strings in the array, you can use a simple for-each loop:
for(String arg:args)
System.out.println(arg);
It's a form of name mangling used for disambiguating method overloads. The method name is appended by a series of characters describing the parameters and return type: the parameters appear sequentially inside parentheses, and the return type follows the closing parenthesis. The codes are as follows:
Z: boolean
B: byte
C: char
S: short
I: int
J: long
F: float
D: double
L fully-qualified-class-name ; : fully qualified class
[ type : array of type
V: void
So according to above codes [Ljava.lang.String;#153c375
Array of string (java.lang.String fully qualified class name) followed by hascode.
String[] args is an Array of Strings and contains the arguments that were given when the application was started. Java does not require you to use the name args, you could just as well specify String[] foo but that will make things unclear if you later read your code again.
Default implementation of toString method for Object is classname;#identityHashCode.
I think, this is what you expect:
System.out.println(java.util.Arrays.toString(args));
It's a string array.
Modify your code to this:
public class Test{
public static void main(String[] args){
System.out.println(args[0]);
}
}
Now compile this code:
$>javac Test.java
Now run:
$>java Test hello
This will print: "hello"
Because "hello" is the argument you are passing to your class.
If you try: args[x], where x=0..n and run your class via command line: java Test your arguments, then you will see any contents which you pass..
The main method has a parameter that is an array of String references.
So each time you try to print args, it gives you memory location of array 'args' because this String array args located a place in memory for array elements.
That say you have an simple program called 'HelloWorld.java' like this:
public class HelloWorld
{
public static void main(String [] args)
{
for(int i =0; i<args.length; i++)
System.out.println(""+args[i]);
}
}
Ready to test this program with command line interface:
java HelloWorld a b c
We can see that this program prints thouse arguments after 'java Helloworld'
a
b
c
Lets make it simple
1: Write a simple class named "test"
public class test {
public static void main(String[] args) {
System.out.println("Passed argument is: " + args[0]);
}
}
2: Now compile it in the following way
javac test.java
3: Now run this by passing an argument
java test Ayoub
** the output will be**
Passed argument is: Ayoub

Java Command line arguments

I am trying to detect whether the 'a' was entered as the first string argument.
Use the apache commons cli if you plan on extending that past a single arg.
"The Apache Commons CLI library provides an API for parsing command line options passed to programs. It's also able to print help messages detailing the options available for a command line tool."
Commons CLI supports different types of options:
POSIX like options (ie. tar -zxvf foo.tar.gz)
GNU like long options (ie. du --human-readable --max-depth=1)
Java like properties (ie. java -Djava.awt.headless=true -Djava.net.useSystemProxies=true Foo)
Short options with value attached (ie. gcc -O2 foo.c)
long options with single hyphen (ie. ant -projecthelp)
public class YourClass {
public static void main(String[] args) {
if (args.length > 0 && args[0].equals("a")){
//...
}
}
}
Every Java program starts with
public static void main(String[] args) {
That array of type String that main() takes as a parameter holds the command line arguments to your program. If the user runs your program as
$ java myProgram a
then args[0] will hold the String "a".
Command-line arguments are passed in the first String[] parameter to main(), e.g.
public static void main( String[] args ) {
}
In the example above, args contains all the command-line arguments.
The short, sweet answer to the question posed is:
public static void main( String[] args ) {
if( args.length > 0 && args[0].equals( "a" ) ) {
// first argument is "a"
} else {
// oh noes!?
}
}
Command line arguments are accessible via String[] args parameter of main method.
For first argument you can check args[0]
entire code would look like
public static void main(String[] args) {
if ("a".equals(args[0])) {
// do something
}
}
Your main method has a String[] argument. That contain the arguments that have been passed to your applications (it's often called args, but that's not a requirement).
Try to pass value a and compare using the equals method like this:
public static void main(String str[]) {
boolean b = str[0].equals("a");
System.out.println(b);
}
Follow this link to know more about Command line argument in Java
As everyone else has said... the .equals method is what you need.
In the off chance you used something like:
if(argv[0] == "a")
then it does not work because == compares the location of the two objects (physical equality) rather than the contents (logical equality).
Since "a" from the command line and "a" in the source for your program are allocated in two different places the == cannot be used. You have to use the equals method which will check to see that both strings have the same characters.
Another note... "a" == "a" will work in many cases, because Strings are special in Java, but 99.99999999999999% of the time you want to use .equals.
Command line arguments are stored as strings in the String array String[] args that is passed tomain()`.
java [program name] [arg1,arg2 ,..]
Command line arguments are the inputs that accept from the command prompt while running the program. The arguments passed can be anything. Which is stored in the args[] array.
//Display all command line information
class ArgDemo{
public static void main(String args[]){
System.out.println("there are "+args.length+"command-line arguments.");
for(int i=0;i<args.length;i++)
System.out.println("args["+i+"]:"+args[i]);
}
}
Example:
java Argdemo one two
The output will be:
there are 2 command line arguments:
they are:
arg[0]:one
arg[1]:two

Categories