question archive A java program which : 1) Read one line at a time and tokenize it using , as a separator 2) Using methods from Matcher and Pattern classes verify that each token matches the specified criteria
Subject:Computer SciencePrice:8.89 Bought3
A java program which :
1) Read one line at a time and tokenize it using , as a separator
2) Using methods from Matcher and Pattern classes verify that each token matches
the specified criteria.
a. For line with all valid fields makes an object of type Student and store that
object in file StudentData.ser
b. For tokens that do not match the specified criteria write the whole line in
error message file named ErrorMsgs.txt and specify what part was wrong.
Contents of the ErrorMsgs.txt file for the above sample data file is given at
the end.
3) When all the lines from the input file are consumed close it, and close
StudentData.ser
4) Re-open StudentData.ser, read one Student object at a time and add it in an
ArrayList. Once all the data is read from StudentData.ser close it.
5) Sort the ArrayList by first by SID, then by Age, then by CGPA in descending
order, and lastly by FirstName and display the result of each as shown in the
sample output.
6) Finally using an Iterator traverse the ArrayList, calculate the average CGPA and
average age of all students and display these two values.
Please find below code
import java.io.BufferedReader; import java.io.Closeable; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStreamWriter; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; import java.util.StringTokenizer; import java.util.regex.Pattern; public class Students { public static final String CNIS_PATTERN = "^[0-9]{5}-[0-9]{7}-[0-9]$"; public static final String SID_PATTERN = "^[A-Z]{2}[0-9]{2}-[A-Z]{3}-[0-9]{3}$"; public static final String AGE_PATTERN = "^(0?[1-9]|[1-9][0-9]|[1][1-9][1-9]|200)$"; public static final String CGPA_PATTERN = "^[0-4].[0-9]{2}$"; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); //somedirpath/students.txt" System.out.println("Enter input file path : "); String inputFilePath = scanner.nextLine(); //somedirpath/StudentData.ser" System.out.println("Enter student data file path : "); String studentDataFilePath = scanner.nextLine(); //somedirpath/ErrorMsgs.txt" System.out.println("Enter errors file path : "); String errorsFilePath = scanner.nextLine(); BufferedReader reader = null; ObjectOutputStream objectOutputStream = null; OutputStreamWriter errorsOutputStream = null; try { System.out.println("starting process for fetching students from file "); reader = new BufferedReader(new FileReader(inputFilePath)); errorsOutputStream = new OutputStreamWriter(new FileOutputStream(errorsFilePath)); objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File(studentDataFilePath))); String line = reader.readLine(); while (line != null) { System.out.println("got line : " +line); try { //preparing student object Student student = validateAndPrepareStudent(line); // writing object to file System.out.println("writing object to StudentData.ser"); objectOutputStream.writeObject(student); } catch (ValidationFailureException e) { System.out.println(e.getMessage()); //writing error to file System.out.println("writing error to ErrorMsgs.txt"); errorsOutputStream.write(e.getMessage()); errorsOutputStream.write("\n"); errorsOutputStream.flush(); } // read next line System.out.println("---------------------------"); line = reader.readLine(); } List<Student> list = getStudentsFromFile(studentDataFilePath); // sorting list of students Collections.sort(list); long totalAge = 0; double totalCGPA = 0; for (Student student: list) { System.out.println("Student info: "+student.toString()); totalAge = (totalAge + student.getAge()); totalCGPA = totalCGPA + student.getCGPA(); } System.out.println("--------------------"); System.out.println("Average age : "+ totalAge/list.size()); System.out.println("Average CGPA : "+ totalCGPA/list.size()); System.out.println("process completed successfully"); } catch (IOException e) { System.out.println(e.getMessage()); } finally { close(objectOutputStream); close(errorsOutputStream); close(reader); } } private static List<Student> getStudentsFromFile(String filePath) { List<Student> students = null; ObjectInputStream oi = null; try { students = new ArrayList<Student>(); oi = new ObjectInputStream(new FileInputStream(new File("/home/sivaprasadt/Videos/CourseHero/Java/students/StudentData.ser"))); Object object = oi.readObject(); while(object != null) { students.add((Student)object); object = oi.readObject(); } } catch (EOFException ex) { } catch(Exception e) { e.printStackTrace(); } finally { close(oi); } return students; } private static void close(Closeable resource) { if (resource != null) { try { resource.close(); } catch (IOException e) { System.out.println("Unable to close resource "+ e.getMessage()); } } } private static Student validateAndPrepareStudent(String line) throws ValidationFailureException { System.out.println("trying to tokenize and setting student object"); StringTokenizer st = new StringTokenizer(line, ","); Student student = new Student(); int noOfTokens = st.countTokens(); for (int i = 1; i <= noOfTokens; i++) { if (i == 1) { String sid = st.nextToken(); if (Pattern.matches(SID_PATTERN, sid)) { student.setSid(sid); } else { throw new ValidationFailureException("Incorrect sid: " + sid + ", line: " + line); } } else if (i == 2) { String firstName = st.nextToken(); if (!firstName.isEmpty()) { student.setFirstName(firstName); } else { throw new ValidationFailureException("First name should name be empty, line: " + line); } } else if (i == 3) { String lastName = st.nextToken(); if (!lastName.isEmpty()) { student.setLastName(lastName); } else { throw new ValidationFailureException("Last name should name be empty, line: " + line); } } else if (i == 4) { String CNIC = st.nextToken(); if (Pattern.matches(CNIS_PATTERN, CNIC)) { student.setCNIC(CNIC); } else { throw new ValidationFailureException("Incorrect CNIC: " + CNIC + ", line: " + line); } } else if (i == 5) { String age = st.nextToken(); if (Pattern.matches(AGE_PATTERN, age)) { student.setAge(Long.parseLong(age)); } else { throw new ValidationFailureException("Invalid age : " + age + ", line: " + line); } } else if (i == 6) { String cgpa = st.nextToken(); if (Pattern.matches(CGPA_PATTERN, cgpa)) { student.setCGPA(Double.parseDouble(cgpa)); } else { throw new ValidationFailureException("Incorrect CGPA: " + cgpa + ", line: " + line); } } } return student; } } class Student implements Serializable, Comparable<Student> { private static final long serialVersionUID = 1L; private String sid; private String firstName; private String lastName; private String CNIC; private long age; private double CGPA; public Student() { } public Student(String sid, String firstName, String lastName, String cNIC, long age, double cGPA) { super(); this.sid = sid; this.firstName = firstName; this.lastName = lastName; CNIC = cNIC; this.age = age; CGPA = cGPA; } public String getSid() { return sid; } public void setSid(String sid) { this.sid = sid; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getCNIC() { return CNIC; } public void setCNIC(String cNIC) { CNIC = cNIC; } public long getAge() { return age; } public void setAge(long age) { this.age = age; } public double getCGPA() { return CGPA; } public void setCGPA(double cGPA) { CGPA = cGPA; } @Override public String toString() { return "SID:" + sid + "\nFirstName: " + firstName + "\nLastName: " + lastName + "\nCNIC: " + CNIC + "\nAge: " + age + "\nCGPA: " + CGPA; } @Override public int compareTo(Student o) { if (o.sid.equals(this.sid)) { if (o.age == this.age) { if (o.CGPA == this.CGPA) { o.firstName.compareTo(this.firstName); } else if (o.CGPA > this.CGPA) { return 1; } else { return -1; } } else if (o.age > this.age) { return 1; } else { return -1; } } else { return o.sid.compareTo(this.sid); } return 0; } } class ValidationFailureException extends Exception { private static final long serialVersionUID = 5602411143312948325L; public ValidationFailureException(String message) { super(message); } }