我想要一个方法或示例从文本文件中读取数据并将其存储到对象数组中。每个对象都有属性(月份名称,数字和布尔数组[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;
}
这是一种逐行读取文件并解析字段的方法。但是,这假定数据文件是正确的(没有丢失的字段,字段的格式正确,等等)。您必须添加代码来创建对象并将其添加到数组。
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句