读入文件中的常量#java
Read in file for constants #java
我想读入一个数据文件,其中有几个常量适用于我的程序(例如 MAXARRAYSIZE)。
然后我希望这些常量可以在我的程序中的任何地方访问,方法是键入类似:ConstantsClassName.MAXARRAYSIZE 的内容。我如何实现这个 class?
一旦从数据文件中分配,这些常量将永远不会在程序执行期间再次更改值。
谢谢。
在 ConstantsClassName
class.
中使用静态块
public class ConstantsClassName{
public static final String MAXARRAYSIZE;
static{
// read your file and store the data in;
MAXARRAYSIZE = valueRetrievedFromFile;
}
}
如果您遵循常量声明的 Java 约定,MAXARRAYSIZE
应该是 MAX_ARRAY_SIZE
。
如果你的文件中有很多常量,你可以使用下面的代码片段:
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();
}
}
现在使用 keyValues HashMap 获取常量的值,例如
keyValues.get("MAXARRAYSIZE");
这样就不用为多个常量定义多个常量变量,只需要keyValues HashMap就可以存储所有的常量及其值。希望对你有帮助。
我想读入一个数据文件,其中有几个常量适用于我的程序(例如 MAXARRAYSIZE)。
然后我希望这些常量可以在我的程序中的任何地方访问,方法是键入类似:ConstantsClassName.MAXARRAYSIZE 的内容。我如何实现这个 class?
一旦从数据文件中分配,这些常量将永远不会在程序执行期间再次更改值。
谢谢。
在 ConstantsClassName
class.
public class ConstantsClassName{
public static final String MAXARRAYSIZE;
static{
// read your file and store the data in;
MAXARRAYSIZE = valueRetrievedFromFile;
}
}
如果您遵循常量声明的 Java 约定,MAXARRAYSIZE
应该是 MAX_ARRAY_SIZE
。
如果你的文件中有很多常量,你可以使用下面的代码片段:
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();
}
}
现在使用 keyValues HashMap 获取常量的值,例如
keyValues.get("MAXARRAYSIZE");
这样就不用为多个常量定义多个常量变量,只需要keyValues HashMap就可以存储所有的常量及其值。希望对你有帮助。