12

I have been working with buffering a file on my local drive to parse and obtain certain data. For test purposes I was easily able to do it this way:

public static void main(String[] args) {

    fileReader fr = new fileReader();
    getList lists = new getList();


    File CP_file = new File("C:/Users/XYZ/workspace/Customer_Product_info.txt");
    int count = fr.fileSizeInLines(CP_file);
    System.out.println("Total number of lines in the file are: "+count);

    List<String> lines = fr.strReader(CP_file);

    ....

}

}

fileReader.java file has the following function:

public List<String> strReader (File in)
{
    List<String> totLines = new ArrayList<String>();

    try
    {
        BufferedReader br = new BufferedReader(new FileReader(in));
        String line;
        while ((line = br.readLine()) != null)
        {
            totLines.add(line);
        }
        br.close();
    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    //String result = null;

    return totLines;
}

Now I want the file path to be passed as a Command line Argument instead. I tried a few things but I am kind of new to this and wasnt able to make it work. Can someone please help and explain what all changes I need to make in order to incorporate that change in my code.

user3495420
  • 121
  • 1
  • 1
  • 3
  • @VivinPaliath : I had tried the below mentioned methods earlier and it threw me an ArrayIndexOutOfBoundException at the line where I am passiong the File(arg[0]) – user3495420 Apr 03 '14 at 23:27
  • 2
    That sounds like you are running the CLI command wrong. Can you post the exact command you are running? Are you calling it on a real CLI or are you running it from another application (such as your IDE)? – Konstantin Tarashchanskiy Apr 04 '14 at 13:45
  • Just like @Konstantin Naryshkin said, how are you using command line arguments ? something like: `java MainClass "C:/Users/XYZ/workspace/Customer_Product_info.txt"` ? (With MainClass being the name of the classe with your main) – Asoub Apr 15 '16 at 08:19

4 Answers4

5

Your problem has two sides: how to pass the parameter from the command line, and how to read it inside your code.

Passing arguments to a Java program

All arguments meant for the actual Java class and not for the JVM, should be put after the class name, like this:

C:\YOUR\WORKSPACE> java your.package.YouMainClass "C:\Users\XYZ\workspace\Customer_Product_info.txt"`

Things to watch out for:

  • Slashes / vs backslashes \: since you're on a Windows system, I'd rather use backslashes for your path, specially if you are including the drive letter. Java can work with both variants, but it's better to follow your SO conventions.
  • Double quotes " to allow for spaces: you'll need to enclose your path in double quotes if any directories contain spaces in their names, so just double quote it every time.
  • Remove final backslash: this only applies to directory paths (file paths can't end in a backslash in Windows). If you write a directory path like this: "C:\My path\XYZ\", the last double quote will be included as part of the path, because of the previous backslash escaping it \". Instead, "C:\My path\XYZ" will do fine.

Reading arguments from your main(String[]) method

Now this one is simple: as others have pointed out, the String with your path should now be in args[0]:

public static void main(String[] args) {

    fileReader fr = new fileReader();
    getList lists = new getList();

    if (args[0] == null || args[0].trim().isEmpty()) {
        System.out.println("You need to specify a path!");
        return;
    } else {
        File CP_file = new File(args[0]);
        int count = fr.fileSizeInLines(CP_file);
        System.out.println("Total number of lines in the file are: "+count);

        List<String> lines = fr.strReader(CP_file);

        ....
    }
}

I added some null-checking to avoid problems like the ArrayIndexOutOfBounds you run into.

Graham
  • 7,431
  • 18
  • 59
  • 84
walen
  • 7,103
  • 2
  • 37
  • 58
3

You need to do this:

public static void main(String[] args) {
    String path = args[0];
    // ... 
    File CP_file = new File(path);
    // ... 
}        
peter.petrov
  • 38,363
  • 16
  • 94
  • 159
2

The complete answer would be something like this :

The below code by path means /etc/dir/fileName.txt

public static void main(String[] args) {
String path = args[0];
// ... 
File CP_file = new File(path);
// ... 

}

But if you want to give just a path and from that path your code to read all your files contained by that directory you would require the above to be exported as a jar file code plus a bat file/ script : bat file example :

FOR %%i IN  (C:/user/dir/*.zip) do (java -cp application.jar;dependencies.jar;...;%%i)

Run the script and your code will run the file / files that are on the path C:/user/dir/*.zip

1

If you want to replace the hard coded path with one that you are passing via the command line, you should just be able to pass it in as a String. Your code will not read:

...
File CP_file = new File(arg[0]);   //Assuming that the path is the first argument
...

Be sure to quote the path on the CLI, especially if it contains white space or other special characters.

  • This is throwing me an ArrayIndexOutOfBoundException at the line where the above mentioned line is. Any further solutions for that? I had tried this earlier as well following a tutorial but didn't solve my problem. Thank you very much for your response. – user3495420 Apr 03 '14 at 23:31