1
votes

I have written one java class and created jar file. I need to pass one parameter to the jar file.

public class parser{
private static final String FILENAME = "C:\\output.txt";

    public static void main(String[] args) throws Exception {
         Scanner scan = new Scanner(new File("C:\\Users\\Desktop\\input.json"));
    //some logic here....
}
}

I have written different methods which will write data to output.txt

I can pass parameter for scan object to jar file and access in the main method using args[] however I want to pass value to FILENAME variable from command line while executing jar command

I am not sure how to do that in java

3
thanks... i actually spent time to google on how to retrieve it :Pashwini

3 Answers

1
votes

In static variable if you want to pass values dynamically you need to remove final modifier in your code. Kindly find below code for more understanding.

import java.util.Scanner;

public class Parser {
    private static String FILENAME = "C:\\output1.txt";

    public static void main(String[] args) throws Exception {
        System.out.println("Before File name : " + FILENAME);
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the new file location ");
        FILENAME = scan.next();
        System.out.println("After File name : " + FILENAME);
        scan.close();
    }
}
1
votes

You may set static final FILENAME with static block. Example:-

private static final String FILENAME;

static{
    FILENAME = "/opt/file.out";
}

From the main method is not possible, since FILENAME is final. To set FILENAME from main method, it must be non final.

private static String FILENAME;

public static void main(String[] args) throws Exception {

    FILENAME = args[0];
}

However keep in mind, that non final class variable is not safe in multithreaded environment.

0
votes

Your main method has that array of strings parameter.

That array contains the arguments that you pass to java when invoking it via the command line.

So your main method should simply check what this array contains, and then use the provided arguments accordingly.

Then you can go:

SomeOtherClass.someStaticField = args[0];

Or

 x = new WhatecerClass(args[1]);