Objectives:

Introduction:

CSV (Comma Separated Values) and JSON (JavaScript Object Notation) are widely used file formats for storing and exchanging data. CSV files store data in a tabular format, separated by commas, while JSON files store data in a key-value format. Java provides libraries for handling both CSV and JSON files, enabling you to read, write, and manipulate data efficiently.

CSV File Format:

CSV files store data in a plain text format, separated by commas. Each line in a CSV file represents a row of data, and each field in the row is separated by a comma. For example, a CSV file containing information about students might have the following structure:

id,name,age,city
1,John Doe,30,New York
2,Jane Smith,25,Los Angeles
3,David Jones,40,Chicago

JSON File Format:

JSON files store data in a key-value format, similar to JavaScript objects. Each object in a JSON file represents a record, and each property of the object is represented by a key-value pair. For example, a JSON file containing information about students might have the following structure:

JSON

{
  "student1": {
    "id": 1,
    "name": "John Doe",
    "age": 30,
    "city": "New York"
  },
  "student2": {
    "id": 2,
    "name": "Jane Smith",
    "age": 25,
    "city": "Los Angeles"
  },
  "student3": {
    "id": 3,
    "name": "David Jones",
    "age": 40,
    "city": "Chicago"
  }
}

Reading CSV and JSON Files:

Java provides libraries for reading CSV and JSON files:

Writing CSV and JSON Files:

To write CSV files, you can use a BufferedWriter and a CSVWriter object. To write JSON files, you can use a GsonBuilder and a Gson object.

Handling Data Parsing and Manipulation:

Once you have read a CSV or JSON file into a data structure, you can parse and manipulate the data using Java’s built-in data types and collections. For example, you can extract specific fields from each record, filter records based on certain criteria, and perform calculations on the data.

Benefits of Using CSV and JSON Files:

CSV and JSON files are lightweight and easy to read and write. They are widely supported by various programming languages and tools. Additionally, CSV files are human-readable, making them suitable for data exchange and sharing.

Summary:

CSV and JSON files are valuable formats for storing and exchanging data in a structured manner. Java provides libraries that simplify the process of reading, writing, and manipulating data from CSV and JSON files. By understanding these concepts, you can effectively handle data-driven applications in Java.

Hands-on Practice

Exercise 1: Reading CSV Data:

Create a program that reads data from a CSV file containing student information and displays it on the console. Use the javacsv library and BufferedReader to read the CSV file.

Java

import java.io.*;
import com.opencsv.CSVParser;
import com.opencsv.CSVReader;

public class ReadCSVData {

    public static void main(String[] args) throws IOException {
        String fileName = "data.csv";

        BufferedReader reader = new BufferedReader(new FileReader(fileName));
        CSVParser csvParser = new CSVParser(reader);
        CSVReader csvReader = new CSVReader(csvParser);

        List<String[]> records = csvReader.readAll();
        for (String[] record : records) {
            for (String field : record) {
                System.out.println(field);
            }
        }

        csvReader.close();
        reader.close();
    }
}

Exercise 2: Writing JSON Data:

Create a program that reads student information from the console and writes it to a JSON file. Use the Gson library to serialize the data into JSON format.

Java

import com.google.gson.GsonBuilder;
import java.io.*;

public class WriteJSONData {

    public static void main(String[] args) throws IOException {
        System.out.println("Enter student details:");
        Scanner scanner = new Scanner(System.in);

        String id = scanner.nextLine();
        String name = scanner.nextLine();
        int age = scanner.nextInt();
        String city = scanner.nextLine();

        scanner.close();

        Student student = new Student(id, name, age, city);
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String jsonData = gson.toJson(student);

        FileWriter fileWriter = new FileWriter("data.json");
        fileWriter.write(jsonData);
        fileWriter.close();
    }
}

Exercise 3: Processing CSV and JSON Data:

Create a program that reads data from both a CSV file and a JSON file, extracts specific information from each record, and compares the values. Use data structures like Map or List to store and manipulate the data.

Java

import java.io.*;
import com.opencsv.CSVParser;
import com.opencsv.CSVReader;
import com.google.gson.Gson;

public class ProcessCSVAndJSONData {

    public static void main(String[] args) throws IOException {
        String csvFileName = "data.csv";
        String jsonFileName = "data.json";

        BufferedReader csvReader = new BufferedReader(new FileReader(csvFileName));
        CSVParser csvParser = new CSVParser(csvReader);
        CSVReader csvReaderCSV = new CSVReader(csvParser);

        List<String[]> csvRecords = csvReaderCSV.readAll();
        for (String[] record : csvRecords) {
            // Extract specific information from each CSV record
        }

        csvReader.close();
        csvReaderCSV.close();

        Reader reader = new FileReader(jsonFileName);
        Gson gson = new Gson();
        Student student = gson.fromJson(reader, Student.class);

        // Extract specific information from the JSON object
    }
}