Header Ads Widget

Responsive Advertisement

File Read and write


 

 

package com.kartik.file.parse;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ReadCVS {

 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<Student>();
  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");
 }

 /**
  *
  * @param csvFile
  *            csvFile
  * @param cvsSplitBy
  *            cvsSplitBy
  * @param studentCourseList
  *            studentCourseList
  * @return br.
  * @throws FileNotFoundException
  *             FileNotFoundException
  * @throws IOException
  *             IOException
  */
 private BufferedReader readFileMethod(String csvFile, String cvsSplitBy,
   List<Student> studentCourseList) throws FileNotFoundException,
   IOException {
  BufferedReader br;
  String line;
  br = new BufferedReader(new FileReader(csvFile));
  while ((line = br.readLine()) != null) {
   // use comma as separator
   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;
 }

 /**
  *
  * @param items
  *            items
  * @throws IOException
  *             IOException
  */
 private void writeFileMethod(Map<String, Student> items) throws IOException {
  File file = new File("D:\\SCC\\studentNewCreate.csv");
  // if file doesnt exists, then create it
  if (!file.exists()) {
   file.createNewFile();
  }
  FileWriter fw = new FileWriter(file.getAbsoluteFile());
  BufferedWriter bw = new BufferedWriter(fw);
  for (Map.Entry<String, Student> entry : items.entrySet()) {
   Student st = entry.getValue();
   bw.write(st.getCourseName() + ": " + st.getMarks());
   bw.newLine();
  }
  bw.close();
 }

 /**
  *
  * @param array
  *            array
  * @return Map<String,Student>
  */
 @SuppressWarnings({ "unchecked", "rawtypes" })
 public static Map<String, Student> processData(List<Student> array) {
  Map<String, Student> retVal = new HashMap<String, Student>();
  Collections.sort(array, new Comparator() {
   public int compare(Object obj1, Object obj2) {
    Student e1 = (Student) obj1;
    Student e2 = (Student) obj2;
    Integer firstId = new Integer(String.valueOf(e1.getId()));
    Integer secndId = new Integer(String.valueOf(e2.getId()));
    int id = firstId.compareTo(secndId);
    int name = e1.getCourseName().compareTo(e2.getCourseName());
    if (id != 0) {
     return id;
    } else if (id == 0 && name != 0) {
     return name;
    }
    return id;
   }
  });
  int countDS = 0, countEng = 0, key = 1;
  for (Student student : array) {
   //Data Structures and English declare in Constant file
   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++;
   }
  }
  countDS = 0;
  countEng = 0;
  key = 1;
  return retVal;
 }
}

 

 

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

  1. Error Handling: Add more granular error handling, such as for parsing errors when converting strings to integers.
  2. Generics in Comparator: The Comparator should ideally use generics to avoid unchecked casts and improve type safety.
  3. Configuration: File paths could be passed as arguments or read from a configuration file to make the program more flexible.
  4. 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

 

 




File Read and write process
File Read and write process





Post a Comment

0 Comments