Read in file for constants #java

前端 未结 2 741
耶瑟儿~
耶瑟儿~ 2021-01-26 17:12

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 som

2条回答
  •  -上瘾入骨i
    2021-01-26 18:05

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

    public static final HashMap 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.

提交回复
热议问题