Код не требует пояснений, если у вас есть какие-либо вопросы, пожалуйста, скажите мне.
File file = new File("Your file's path");
Scanner sc=null;
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ArrayList<Student> list = new ArrayList<>();
while(sc.hasNextLine()){
if(sc.nextLine().equalsIgnoreCase("student")){
//Assuming each property is in the seperate line of file
String id,name,surname=null;
if(sc.hasNextLine()){
id = sc.nextLine();
/*if id is int use
* int id = Integer.parseInt(sc.nextLine());
*/
}
if(sc.hasNextLine()){
name = sc.nextLine();
}
if(sc.hasNextLine()){
surname = sc.nextLine();
}
list.add(new Student(id,name,surname));
}
}
Использование bufferedReader:
InputStream in = new FileInputStream("Your file's path");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String str;
ArrayList<Student> list = new ArrayList<>();
while((str=br.readLine())!=null){
if(str.equalsIgnoreCase("student")){
String id=null,name=null,surname=null;
if((str=br.readLine())!=null){
id = str;
/*if id is int use
* int id = Integer.parseInt(sc.nextLine());
*/
}
if((str=br.readLine())!=null){
name = str;
}
if((str=br.readLine())!=null){
surname = str;
}
list.add(new Student(id,name,surname));
}
}
С ObjectInputStream
OutputStream out = new FileOutputStream("yourfilepath.bin");
ObjectOutputStream outputStream = new ObjectOutputStream(out);
Student s1 = new Student("100383", "JOHN", "MITCHELL");
Student s2 = new Student("100346", "AMY", "CHING");
outputStream.writeObject(s1);
outputStream.writeObject(s2);
outputStream.writeObject(null);//to realize that you reach the end of file
outputStream.close();
out.close();
InputStream in = new FileInputStream("yourfilepath.bin");
ObjectInputStream inputStream = new ObjectInputStream(in);
Student temp = null;
while((temp =(Student)inputStream.readObject())!=null){
System.out.println(temp.id+","+temp.name+","+temp.surname);
}
ВЫХОД
100383, ДЖОН, МИТЧЕЛЛ
100346, ЭМИ, ЧИНГ