I started using eclipse in my macbook pro and wrote program that needs args like (3 1 5) to work . The program already compiled using eclipse . how can i run it through Terminal with args? more specific : what i need to do for operate it with file that contain the info. like batch file in windows? I am new in the java world so please keep it simple as you can.
Asked
Active
Viewed 3,986 times
1 Answers
0
For an Example.java program with args 3 1 5, enter
java Example 3 1 5
into Terminal. These arguments will be passed into your Example class's
public static void main(String[] args)
method as the string array {"3", "1", "5"}
.
Alternatively, to accept arguments from a file instead of from Terminal, you might try specifying a configuration file as a program argument:
java Example args.txt
and then in the Example class, do something like:
public static void main(String[] args) throws FileNotFoundException {
String filename = args[0];
Scanner scanner = new Scanner(new File(filename));
int firstArg = scanner.nextInt();
int secondArg = scanner.nextInt();
int thirdArg = scanner.nextInt();
//etc.
}

Hans Brende
- 7,847
- 4
- 37
- 44
-
thank you but what i need to write in the configuration file as a program argument? – FuxsA Jul 28 '14 at 15:09
-
@FuxsA you can write whatever you want in the configuration file, as long as you parse it correctly in your code. In my example above, you would simply write "3 1 5" in the configuration file, which would be assigned to `firstArg`, `secondArg`, and `thirdArg`, respectively. – Hans Brende Jul 28 '14 at 16:08