Studentsreader.java 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import java.util.ArrayList;
  2. import java.io.BufferedReader;
  3. import java.io.FileReader;
  4. import java.io.IOException;
  5. public class Studentsreader {
  6. // reads specified file, returns a Classroom following the csv format
  7. public Classroom read(String file) throws IllegalCSVStructureException {
  8. // some variables
  9. boolean header = true;
  10. int optsubcount = 0;
  11. String[] optsubjects = null;
  12. ArrayList<Student> students = new ArrayList<Student>();
  13. // file io
  14. try (BufferedReader br = new BufferedReader(new FileReader(file))) {
  15. for (String line; (line = br.readLine()) != null;) {
  16. // if we're currently at the header of our csv file, which *should*
  17. // be true for the first line of every csv file ever
  18. if (header) {
  19. header = false;
  20. String[] splitheader = line.split(";");
  21. // keep count of optional subjects
  22. // 3 positional fields are always required, nr, lastname and surname
  23. optsubcount = splitheader.length - 3;
  24. // check for invalidity of file
  25. if (optsubcount < 0)
  26. throw new IllegalCSVStructureException("source CSV is missing the minimum required fields");
  27. optsubjects = new String[optsubcount];
  28. // for optsubjects
  29. for (int i = 0; i < optsubcount; i++) {
  30. optsubjects[i] = splitheader[i + 3];
  31. }
  32. } else {
  33. // if line is anything that isn't the header
  34. String[] splitline = line.split(";", -1);
  35. // hardcoded required fields
  36. String nr = null, lastname = null, surname = null;
  37. // optional subjects
  38. Boolean[] visitsoptsubs = new Boolean[optsubcount];
  39. // iterate line contents
  40. for (int i = 0; i < optsubcount + 3; i++) {
  41. switch (i) {
  42. case 0:
  43. nr = splitline[i];
  44. continue;
  45. case 1:
  46. lastname = splitline[i];
  47. continue;
  48. case 2:
  49. surname = splitline[i];
  50. continue;
  51. default:
  52. if (!"".equals(splitline[i]))
  53. visitsoptsubs[i - 3] = true;
  54. else
  55. visitsoptsubs[i - 3] = false;
  56. continue;
  57. }
  58. }
  59. students.add(new Student(nr, lastname, surname, visitsoptsubs));
  60. }
  61. }
  62. } catch (IOException e) {
  63. // stuff happened I guess
  64. }
  65. // create and populate classroom
  66. Classroom classroom = new Classroom(students.toArray(new Student[students.size()]), optsubjects);
  67. return classroom;
  68. }
  69. }