首页 > 解决方案 > 如何从 .t​​xt 存储用户数据以进行处理?

问题描述

假设我有一个文本文件,其中包含

1个学生证

2-名字

3- 姓氏

4- 城市

5-性别

它们用逗号分隔,每一行信息的顺序都与其他信息相同。

例如,我需要单独存储城市,这样我就可以知道他们是否适合旅行(他们指定了特定的城市)。

文本文件中的示例:

1234567890,莎拉,约翰逊,女,俄勒冈州

1029384756,约翰·皮特,男,坦帕

我使用哪种类型的列表?以及如何分隔该列表中的每个信息?

标签: javadata-structures

解决方案


private static class Student{
    private long studentId;
    private String firstName;
    private String lastName;
    private String city;
    private String gender;


    public static Student parseLine(String line){
      String[] properties = line.split(", ");
      Student student = new Student();
      student.studentId = Long.parseLong(properties[0]);
      student.firstName = properties[1];
      student.lastName = properties[2];
      student.city = properties[3];
      student.gender = properties[4];
      return student;
    }

    public static Collection<Student> readFile(String path) throws IOException {

      return Files.lines(Paths.get(path)).map(Student::parseLine).collect(Collectors.toList());

    }

推荐阅读