我是编程界的新手,现在我正在编写一个简单的代码来读取每行存储学生姓名和年龄的文本文件。出于某种原因,我需要读取该文件两次,所以我想问有没有比这更简单的方法?
File inputFile = new File("students.txt");
try {
Scanner in = new Scanner (inputFile);
// count how many lines are in the file
while (in.hasNext())
{
in.nextLine();
count++;
}
in.close();
} catch (FileNotFoundException e) {
System.out.println ("Check your file mate");
}
ArrayStudent s = new ArrayStudent(count);
try {
Scanner in2 = new Scanner (inputFile);
while (in2.hasNext())
{
String name = in2.next();
int age = in2.nextInt();
s.insertStudent(new Student (name, age));
}
in2.close();
} catch (FileNotFoundException e) {
System.out.println ("Check your file mate");
}