package
com.kartik.file.parse; Step 2> package
com.kartik.file.parse; public class
Student { private int id; private String
courseName; private int marks; /** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(int id) { this.id = id; } /** * @return the courseName */ public String getCourseName() { return courseName; } /** * @param courseName the courseName to
set */ public void setCourseName(String
courseName) { this.courseName = courseName; } /** * @return the marks */ public int getMarks() { return marks; } /** * @param marks the marks to set */ public void setMarks(int marks) { this.marks = marks; } } |
The code consists of two classes: ReadCVS
and Student. The ReadCVS class is responsible for reading data from a text
file, processing it, and writing the output to another file. The Student class
serves as a simple data model holding id, courseName, and marks for each
student.
Step-by-Step Breakdown
1. Student Class
The Student class is a plain Java object (POJO) with private
fields for id, courseName, and marks, along with their corresponding getter and
setter methods. This class encapsulates the student data and provides methods
to access and modify these fields.
java
public class
Student { private int id; private String courseName; private int marks; // Getters and Setters } |
2. ReadCVS Class
This class performs the main logic of reading from and
writing to files, as well as processing the data.
- File
Reading (readFileMethod):
- The
method readFileMethod reads each line from a CSV file, splits the line by
the specified delimiter (|), and populates a list of Student objects.
Java
private
BufferedReader readFileMethod(String csvFile, String cvsSplitBy, List<Student> studentCourseList)
throws FileNotFoundException, IOException { BufferedReader br = new
BufferedReader(new FileReader(csvFile)); String line; while ((line = br.readLine()) != null) { String[] student =
line.split(cvsSplitBy); Student stdnt = new Student();
stdnt.setId(Integer.parseInt(student[0])); stdnt.setCourseName(student[1]);
stdnt.setMarks(Integer.parseInt(student[2])); studentCourseList.add(stdnt); } return br; } |
- File
Writing (writeFileMethod):
- This
method writes the processed student data to an output file (studentNewCreate.csv).
java
private void
writeFileMethod(Map<String, Student> items) throws IOException { File file = new
File("D:\\SCC\\studentNewCreate.csv"); if (!file.exists()) { file.createNewFile(); } BufferedWriter bw = new
BufferedWriter(new FileWriter(file)); for (Map.Entry<String, Student>
entry : items.entrySet()) { Student st = entry.getValue(); bw.write(st.getCourseName() + ":
" + st.getMarks()); bw.newLine(); } bw.close(); } |
- Data
Processing (processData):
- The processData
method sorts the list of Student objects by id and then by courseName. It
then picks the first student found for each of the courses "Data
Structures" and "English" and stores them in a Map.
Java
public static
Map<String, Student> processData(List<Student> array) { Map<String, Student> retVal = new
HashMap<>(); Collections.sort(array, new
Comparator<Student>() { public int compare(Student e1,
Student e2) { int idCompare =
Integer.compare(e1.getId(), e2.getId()); if (idCompare != 0) { return idCompare; } return
e1.getCourseName().compareTo(e2.getCourseName()); } }); int countDS = 0, countEng = 0, key = 1; for (Student student : array) { if
(student.getCourseName().equalsIgnoreCase("Data Structures")
&& countDS == 0) { retVal.put(String.valueOf(key),
student); key++; countDS++; } if
(student.getCourseName().equalsIgnoreCase("English") &&
countEng == 0) { retVal.put(String.valueOf(key),
student); key++; countEng++; } } return retVal; } |
- Main
Method:
- The main
method orchestrates the entire process. It creates an instance of ReadCVS,
calls the methods to read the input file, processes the data, and writes
the output.
java
public static
void main(String[] args) throws FileNotFoundException, IOException { ReadCVS obj = new ReadCVS(); obj.run(); } public void
run() { String csvFile =
"D:\\SCC\\studentData.txt"; BufferedReader br = null; String cvsSplitBy = "\\|"; List<Student> studentCourseList =
new ArrayList<>(); try { br = readFileMethod(csvFile,
cvsSplitBy, studentCourseList); Map<String, Student> items =
processData(studentCourseList); writeFileMethod(items); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } System.out.println("Done"); } |
Summary
- File
Reading: The program reads the student data from a CSV file and
populates a list of Student objects.
- Data
Processing: It processes the list, sorting the students by id and courseName,
and then selects specific students for output.
- File
Writing: Finally, the selected student data is written to a new CSV
file.
Potential Improvements
- Error
Handling: Add more granular error handling, such as for parsing errors
when converting strings to integers.
- Generics
in Comparator: The Comparator should ideally use generics to avoid
unchecked casts and improve type safety.
- Configuration:
File paths could be passed as arguments or read from a configuration file
to make the program more flexible.
- Constants:
The course names "Data Structures" and "English"
should be declared as constants to avoid hardcoding.
Output:
CSV file .......................................... 22,Data
Structures,45 23,English,52 22,English,51 26,Data
Structures,72 23,Data
Structures,61 21,English,81 |
0 Comments