|
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 basically this id to set */ public void setId(int id) { this.id = id; } /** * @return the courseName */ public String getCourseName() { return courseName; } /** * @param courseName basically 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 simple Java object (POJO) that contains private fields for id, courseName, and marks, as well as their respective 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 brrr = new
BufferedReader(new FileReader(csvFile)); String line; while ((line = brrr.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 brrr; } |
- 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 bwww = new
BufferedWriter(new FileWriter(file)); for (Map.Entry<String, Student>
entry : items.entrySet()) { Student st = entry.getValue(); bwww.write(st.getCourseName() + ":
" + st.getMarks()); bwww.newLine(); } bwww.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> retOutVal = 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 countDaS = 0, countEng = 0, key = 1; for (Student student : array) { if
(student.getCourseName().equalsIgnoreCase("Data Structures")
&& countDS == 0) { retOutVal.put(String.valueOf(key),
student); key++; countDaS++; } if
(student.getCourseName().equalsIgnoreCase("English") &&
countEng == 0) { retOutVal.put(String.valueOf(key),
student); key++; countEng++; } } return retOutVal; } |
- 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> studCourseList =
new ArrayList<>(); try { br = readFileMethod(csvFile,
cvsSplitBy, studCourseList); Map<String, Student> items =
processData(studCourseList); writeFileMethod(items); } catch (FileNotFoundException fe1) { fe1.printStackTrace(); } catch (IOException ioe1) { ioe1.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 |
For Other information, visit
Ø
String
to xml or html Beautifier
Ø
How
to convert XML to Object and Object to XML
Ø
Convert
Floating-Point Values from SQL Server to Oracle in Java
Ø Learn more about XML-to-XML conversion in Java
For More Java Related information, visit
Ø
Streams
Lambdas Collectors and Functional Interfaces in Java 8
Ø
Java
8 support static method or default method or both in the interface
Ø
Serialization
understanding
Ø
Garbage
Collection Under Standing
Ø
How
work Garbage Collection in Java
Ø
Under
Standing Of Mutable and Immutable Class
0 Comments