0

I want to read in a datafile that has several constants for my program (e.g. MAXARRAYSIZE).
I then want these constants to be accessible anywhere in my program by typing something like: ConstantsClassName.MAXARRAYSIZE. How do I implement this class?

Once assigned from the datafile, these constants will never again change value during program execution.

Thanks.

user1714575
  • 31
  • 1
  • 4
  • 2
    you can create a properties file and add your constant name and value as key-value pairs. Then use resourcebundle class to read the data. [this link](https://docs.oracle.com/javase/tutorial/i18n/resbundle/concept.html) explains the concept. [an example](https://examples.javacodegeeks.com/core-java/util/resourcebundle/java-resourcebundle-example/) – Laxman Nov 21 '16 at 16:46

2 Answers2

0

Use a static bloc in ConstantsClassName class.

public class ConstantsClassName{
    public static final  String MAXARRAYSIZE;
    static{
        // read your file and store the data in;
        MAXARRAYSIZE = valueRetrievedFromFile;
    }
}

MAXARRAYSIZE should be MAX_ARRAY_SIZE if you follow Java conventions for constants declaration.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
0

If their are lots of constants in your file, you can use below snippet of code:

public static final HashMap<String, String> keyValues = new HashMap<>();
static{
    BufferedReader br = null;
    String line = null;
    try{
        br = new BufferedReader(new FileReader("datafile.txt"));
        while((line=br.readLine())!=null){
            //if Constant name and Value is separated by space
            keyValues.put(line.split(" ")[0], line.split(" ")[1]);
        }
    }catch(IOException e){
        e.printStackTrace();
    }
}

Now use the keyValues HashMap to get the value you have for the constant like

keyValues.get("MAXARRAYSIZE");

In this way you do not have to define multiple constant variables for multiple constants, only keyValues HashMap is sufficient to store all the constants and its value. Hope it helps.

SachinSarawgi
  • 2,632
  • 20
  • 28