我正在使用以下代码从文件中读取
int lineNumber = 0;
try{
BufferedReader in = new BufferedReader (new FileReader("electric.txt"));
String line = null;
while((line = in.readLine()) != null){
lineNumber++;
system.out.println("Line "+ lineNumber + " : "+ line);
}
} catch(IOException e){
e.printStackTrace();
}
我的文件在每一行都有特定的值,例如第一行是int,第二个字符串,第三个布尔等...
我的问题是如何在变量中获取每种数据类型?
基本上,在一种天真的方法中,您只需要根据需要进行多次读取:
String firstLine = in.readLine();
String secondLine = in.readLine();
...
然后你可以这样做:
Whatever dataObject = new Whatever(firstLine, secondLine, ...);
例如(可能在一个循环中,因为您可能想要读取许多数据对象的数据,而不仅仅是一个数据对象)。
换句话说:您在某些辅助变量中读取所需的属性,然后将这些属性推送到要填充数据的对象中。优点:这适用于非常大的数据,因为您一次只能阅读几行。缺点:你必须担心无效文件,缺少行和这些事情(所以你需要相当多的错误处理)。
或者:首先将整个文件读入内存,例如使用List<String> allLines = java.util.Files.readAllLines(somePathToYourFile);
然后,迭代这些allLines
进一步处理您的内容,现在不用担心IOExceptions。
如果要检查行是布尔值,整数还是字符串,这是一种可能的解决方案。如果您需要检查线路是长还是短,双线或浮线等,您仍然需要处理这些情况。
System.out.println(“Line”+ lineNumber +“:”+ line +“,Datatype:”+ typeChecker(line));
public static String typeChecker(String line){
if (line.equals("true")||line.equals("false"))
return "boolean";
else{ if (isInteger(line))
return "int";
}
return "String";
}
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
return true;
}