我想要一个方法或一个例子来从文本文件中读取数据并将它们存储到对象数组中。每个对象都有属性(月份名称,数字和布尔数组[3])。
文本文件逐行包含此信息(月份名称,数字和布尔数组):
May
211345
true false true
June
8868767
false true false
课程:
public class A{
private String monthName;
private int number;
private boolean[] working;
public data() { ... }
}
publlic class B {
private A[] a;
}
答案 0 :(得分:0)
这是一种逐行读取文件并解析字段的方法。这假设数据文件是正确的(没有丢失字段,字段格式正确等)。您必须添加代码才能创建对象并将其添加到数组中。
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
public class ReadFile {
public static void main(String[] args) {
String fileFullPath = "C:\\Temp\\data.txt";
/** verify that file exists */
File checkFile = new File(fileFullPath);
if (!checkFile.exists()) {
System.err.println("error - file does not exist");
System.exit(0);
}
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(fileFullPath));
String line;
/** keep reading lines while we still have some */
String month;
int number;
boolean[] barr;
while ((line = br.readLine()) != null) {
month = line;
line = br.readLine();
number = Integer.parseInt(line);
line = br.readLine();
String[] arr = line.split("\\s");
barr = new boolean[3];
for (int i=0; i < arr.length; i++) {
barr[i] = Boolean.parseBoolean(arr[i]);
}
/** store the fields in your object, then add to array **/
System.out.println(month);
System.out.println(number);
System.out.println(Arrays.toString(barr));
System.out.println();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} //end main()
} //end