Search code examples
javaexecution

How to provide java program with external files when executing the run command in console?


So it might seem like a trivial question, but I cannot find any information out there that answers my question. Nonetheless, it is a very general coding question.

Suppose you have a java program that reads a file and creates a data structure based on the information provided by the file. So you do:

javac javaprogram.java
java javaprogram

Easy enough, but what I want to do here is to provide the program with a file specified in the command line, like this:

javac javaprogram.java
java javaprogram -file

What code do I have to write to conclude this very concern? Thanks.


Solution

  • One of the best command-line utility libraries for Java out there is JCommander.

    A trivial implementation based on your thread description would be:

    public class javaprogram {
    
        @Parameter(names={"-file"})
        String filePath;
    
        public static void main(String[] args) {
            // instantiate your main class
            javaprogram program = new javaprogram();
    
            // intialize JCommander and parse input arguments
            JCommander.newBuilder().addObject(program).build().parse(args);
            
            // use your file path which is now accessible through the 'filePath' field
        }
    
    }
    

    You should make sure that the library jar is available under your classpath when compiling the javaprogram.java class file.

    Otherwise, in case you don't need an utility around you program argument, you may keep the program entry simple enough reading the file path as a raw program argument:

    public class javaprogram {
    
        private static final String FILE_SWITCH = "-file";
    
        public static void main(String[] args) {
            if ((args.length == 2) && (FILE_SWITCH.equals(args[0]))) {
                final String filePath = args[1];
                // use your file path which is now accessible through the 'filePath' local variable
            }
        }
    
    }