java中怎么把记事本中数据读取其中信息并存入学生集合list中去
时间: 2024-02-05 22:11:12 浏览: 165
可以使用Java的File类和Scanner类来实现从记事本中读取数据并存入学生集合List中。具体步骤如下:
1. 创建一个File对象,指定记事本文件的路径。
```java
File file = new File("path/to/your/file.txt");
```
2. 创建一个Scanner对象,用于读取文件中的数据。然后循环读取文件中的每一行数据,并将其分割成学生的各个属性,最后创建一个学生对象并将其添加到学生集合List中。
```java
Scanner scanner = new Scanner(file);
List<Student> studentList = new ArrayList<>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] data = line.split(",");
String name = data[0];
int age = Integer.parseInt(data[1]);
String gender = data[2];
Student student = new Student(name, age, gender);
studentList.add(student);
}
```
这里假设文件中每一行的格式为`name,age,gender`,其中name为字符串类型,age为整数类型,gender为字符串类型。
3. 最后记得关闭Scanner对象。
```java
scanner.close();
```
完整代码示例:
```java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("path/to/your/file.txt");
Scanner scanner = new Scanner(file);
List<Student> studentList = new ArrayList<>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] data = line.split(",");
String name = data[0];
int age = Integer.parseInt(data[1]);
String gender = data[2];
Student student = new Student(name, age, gender);
studentList.add(student);
}
scanner.close();
// do something with studentList
}
}
class Student {
private String name;
private int age;
private String gender;
public Student(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
// getters and setters
}
```
阅读全文