1

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

1
  • thanks... i actually spent time to google on how to retrieve it :P Commented Aug 10, 2018 at 22:11

3 Answers 3

1

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();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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]);

1 Comment

yeah but we can access those values inside main method only right what about variables declared outside of main method?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.