简体   繁体   English

读取文件中的常量#java

[英]Read in file for constants #java

I want to read in a datafile that has several constants for my program (eg MAXARRAYSIZE). 我想读取一个数据文件,该文件的程序具有多个常量(例如MAXARRAYSIZE)。
I then want these constants to be accessible anywhere in my program by typing something like: ConstantsClassName.MAXARRAYSIZE. 然后,我希望通过键入类似ConstantsClassName.MAXARRAYSIZE的内容在程序中的任何位置访问这些常量。 How do I implement this class? 我如何实施该课程?

Once assigned from the datafile, these constants will never again change value during program execution. 一旦从数据文件中分配了这些常量,它们将在程序执行期间不再更改值。

Thanks. 谢谢。

Use a static bloc in ConstantsClassName class. ConstantsClassName类中使用静态块。

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. 如果您遵循Java约定的常量声明,则MAXARRAYSIZE应该为MAX_ARRAY_SIZE

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 HashMap来获取常量的值,例如

keyValues.get("MAXARRAYSIZE"); 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. 这样,您不必为多个常量定义多个常量变量,只需keyValues HashMap即可存储所有常量及其值。 Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM