How can I receive a file as a command-line argument?
Just the path of the file is passed, inside your program use the Java File class to handle it
This takes the first parameter as the file path:
import java.io.File;
public class SomeProgram {
public static void main(String[] args) {
if(args.length > 0) {
File file = new File(args[0]);
// Work with your 'file' object here
}
}
}
in Java, the main
method receives an array of String as argument, as you probably have noticed. you can give another name to the parameter args
, but this is the most used one.
the array args
contains the values of what the user has typed when launching your program, after the class name. for example, to run a class named Foo, the user must type:
[user@desktop ~]$ java Foo
everything the user types after the class name is considered to be a parameter. for example:
[user@desktop ~]$ java Foo bar baz
now your program has received two parameters: bar and baz. those parameters are stored in the array args
. as a regular Java array, the first parameter can be retrieved by accessing args[0]
, the second parameter can be retrieved by accessing args[1]
, and so on. if you try to access an invalid position (when the user didn't type what you expected), that statement will throw an ArrayIndexOutOfBoundsException
, just like it would with any array. you can check how many parameters were typed with args.length
.
so, back to your question. the user may inform a file name as a command line parameter and you can read that value through the argument of the main
method, usually called args
. you have to check if he really typed something as an argument (checking the array length), and if it's ok, you access args[0]
to read what he's typed. then, you may create a File
object based on that string, and do what you want to do with it. always check if the user typed the number of parameters you are expecting, otherwise you'll get an exception when accessing the array.
here's a full example of how to use command line parameters:
public class Foo {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("no arguments were given.");
}
else {
for (String a : args) {
System.out.println(a);
}
}
}
}
this class will parse the parameters informed by the user. if he hasn't type anything, the class will print the message "no arguments were given." if he informs any number of parameters, those parameters will be shown on the screen. so, running this class with the two examples I've given on this answer, the output would be:
[user@desktop ~]$ java Foo
no arguments were given.
[user@desktop ~]$ java Foo bar baz
bar
baz