[英]How to assign file content into a variable in Java
我有一个.txt文件,其中存在各种变量(每个变量都由一行分隔)。 我需要读取.txt文件并将其分配给txt文件中的相应变量。 无需相同顺序
input.txt
int a=3;
boolean b=true;
String sr = "Hai";
我尝试过的
int a;
boolean b;
String sr;
String CurrentLine;
br = new BufferedReader(new FileReader("C:\\input.txt"));
while ((CurrentLine = br.readLine()) != null) {
\\ need to read assign variables to corresponding variables in test file
}
是否可以在文件中声明变量并在main()中读取?
如果可以的话,建议您如下更改文件格式:
input.properties
a=3
b=true
sr=Hai
并使用如下代码:
Properties prop = new Properties();
prop.load(new FileInputStream("intput.properties"));
int a = Integer.parseInt(prop.getProperty("a", "0"));
boolean b = Boolean.parseBoolean(prop.getProperty("b", "false"));
String sr = prop.getProperty("sr");
您可以执行以下操作(但这是awfaul的易碎代码,没有任何形式的异常处理):
if (CurrentLine.startsWith("boolean")) {
String str = CurrentLine.substring(0, CurrentLine.length()-1);
String[] sa = str.split("=");
b = Boolean.parseBoolean(sa[1].trim());
}
else if (CurrentLine.startsWith("int"))
//...
如注释中所述,您应该使用某种结构化文件格式(如果可能)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.