从一个文本文件output.txt读取数据并转换为List<Person>集合 文本文件的格式为: 1 阿会喃 云南 男 190 225 74 2 伊籍 江陵 男 162 226 24
时间: 2024-05-07 16:16:21 浏览: 97
我可以回答你的问题。以下是从文本文件output.txt读取数据并转换为List<Person>集合的代码:
```
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
List<Person> people = readPeopleFromFile("output.txt");
// do something with the List<Person>
}
public static List<Person> readPeopleFromFile(String filename) {
List<Person> people = new ArrayList<>();
try {
File file = new File(filename);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] parts = line.split("\\s+");
int id = Integer.parseInt(parts[0]);
String name = parts[1];
String city = parts[2];
char gender = parts[3].charAt(0);
int height = Integer.parseInt(parts[4]);
int weight = Integer.parseInt(parts[5]);
int age = Integer.parseInt(parts[6]);
Person person = new Person(id, name, city, gender, height, weight, age);
people.add(person);
}
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
return people;
}
}
class Person {
private int id;
private String name;
private String city;
private char gender;
private int height;
private int weight;
private int age;
public Person(int id, String name, String city, char gender, int height, int weight, int age) {
this.id = id;
this.name = name;
this.city = city;
this.gender = gender;
this.height = height;
this.weight = weight;
this.age = age;
}
// getters and setters omitted for brevity
}
```
这段代码会读取名为output.txt的文本文件,将每一行的数据转换为一个Person对象,并将所有Person对象存储在List<Person>集合中。如果你需要使用这个List<Person>集合,你可以在main()方法中调用readPeopleFromFile()方法,然后对List<Person>进行操作。
阅读全文