aPugLife
aPugLife

Reputation: 1039

Parsing a file passed as argument to Java from command line

I am trying to follow this link: Parsing arguments to a Java command line program

and use arguments in java to parse some file.

The file I need to feed to the application are, mainly, 2. Let's call them file1 and file2.

I wish I can call the java like:

/usr/bin/java -jar myapplication.jar -f file1

or

/usr/bin/java -jar myapplication.jar -s file2

Never ever at the same time.

In that link I posted, I can not understand how to pass an argument, which is a file, to the void main.

My code before understanding that I need arguments in -f -s format:

public class myApp {
    public static void main(String[] args) throws IOException, JAXBException, SQLException {
        Database db = new Database();
        if ( args.length == 0 ) {
            System.out.println("No arguments were given.\n");
            db.disconnect();
        }
        else {
            System.out.println("Got the argument.\n");
            File file = new File(args[0]);
            String namefile = file.getName();

            switch (namefile.substring(0, 6)) {
                case "FILE01":
                    System.out.println("Processing file type FILE01: "+namefile);
                    Process_filezeroone program_zeroone = new Process_filezeroone();
                    program_zeroone.process(file, namefile);
                    break;
                case "FILE02":
                    System.out.println("Processing file type FILE02: "+namefile);
                    Process_filezerotwo program_zerotwo = new Process_filezerotwo();
                    program_zerotwo.process(file, namefile);
                    break;
                default:
                    System.out.println("Skipping: "+namefile);
                    db.disconnect();
            }
        }
    }
}

Thank you for any help.

Upvotes: 0

Views: 1833

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533710

In the first case you have the same as

myApp.main(new String[] { "-f", "file1" });

and in the second case

myApp.main(new String[] { "-s", "file2" });

If you find the arguments confusing I suggest you use your debugger to look at the array or print out the arguments.

You can use a switch to switch between them or use a couple of if / else if statements.

Upvotes: 0

Turamarth
Turamarth

Reputation: 2282

Just do a switch case on the first argument (-f/-s).

File file;
switch(args[0]){
    case "-f" : 
        file = new File(args[1]);
        //do stuff with file1
        break;
    case "-s" : 
        file = new File(args[1]);
        //do stuff with file2
        break;
    default :
}

Upvotes: 3

mutou
mutou

Reputation: 51

It's very simple. Just use java.io.File api to implement this.

File f = new File(args[0]);

and the use InputStream to manipulate file.

Upvotes: 0

Related Questions