Home > Blockchain >  (java)how to store user data from .txt to work on it?
(java)how to store user data from .txt to work on it?

Time:10-01

lets say, I have a text file that contains

1-student ID

2-First Name

3- Last Name

4- City

5- gender

they're separated by commas and every line of information has the same sequence as all the others

I need to store the city for instance alone so I can know if they're a good candadate for the trip (they specified specific cities)

Example from the text file:

1234567890, Sarah, Johnson, female, Oregon

1029384756, John, Pitt, male, Tampa

which type of list do I use? and how can I separate each info in that list?

CodePudding user response:

Your file is basically CSV (comma separated values), so in your case I'd use the OpenCsv library to parse the data.

If you don't want to use library you can read the lines Files.lines(...) and then for each line use line.split(',').

CodePudding user response:

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());

    }
  • Related