Saturday, December 28, 2024
Google search engine
HomeLanguagesJavaHow to Read Write Object’s Data in CSV Format Using Notepad in...

How to Read Write Object’s Data in CSV Format Using Notepad in Java?

The CSV stands for Comma-Separated Values. CSV files can be used with almost any spreadsheet program, such as Microsoft Excel or Google Spreadsheets. They differ from other spreadsheet file types because you can only have a single sheet in a file, they can not save cell, column, or row. Also, you cannot save formulas in this format.

Now, to store or to write the data member’s value of an object in a fixed format implies that a record of a fixed length in a file, we can use the combination of FileWriter, BufferedWriter, and String.format() where the String.format() method returns the formatted string by a given locale, format, and argument. The java string format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string.

Approach:

A. File Reading

  1. Open a file (using the fully qualified name of the file) using FileReader & BufferedReader.
  2. Use the split() method to split the data that was read in commaseparated format.
  3. Read the individual split values.
  4. Print the values.
  5. Close both the Readers.

B. File Writing 

  1. Create any class Object & assign values to its data members.
  2. Create & open a file (using the fully qualified name of the file) in append mode using FileWriter & BufferedWriter.
  3. Use the String.format() method to create a string of a fixed format containing the values of data members of the object to be written. (The format should contain “,” to store the string in CSV format)
  4. Write the formatted string to the file using write() method of BufferedWriter Class.
  5. Close both the Writers.

Implementation: Here we are considering a Customer class having 2 data members namely ‘name’ and ‘account_No’. While reading we need to read the data that was written in CSV format in the file & split that data read. While writing we need to save the value of each data member for every object of Customer type (in CSV format ) in a file named “CustomerData.txt”. We are creating a String format that contains 30 bytes of file for Customer’s name & 10 bytes for Customer’s account_No (to save every object’s data members in the same format) using format() method of String class. For example:

String.format("%30s ,%10d",name, acc_No);

Note: replaceAll() method is used to remove all the white spaces (//s in Unicode) from the data read.

Example:

Java




// Java Program to Read Write Object's Data in CSV Format
// of FIxed Length Records using Notepad
 
// Importing input output classes
import java.io.*;
// Importing Scanner class to take input from user
import java.util.Scanner;
 
// Class 1
// Helper class
class Customer {
 
    // Member variables
    private String name = null;
    private long account_No;
    private static long auto_Generate_AccNo = 100;
 
    // Constructor of this class
    Customer(String nm)
    {
        account_No = auto_Generate_AccNo;
        auto_Generate_AccNo++;
        name = nm;
    }
 
    // Methods of this class
    public String getCustomerName() { return name; }
    public long getAccNo() { return account_No; }
}
 
// Class 2
// Main Class
public class Main {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Custom input character
        char ch = 'y';
        int menuCh = 0;
        int exitStatus = 0;
 
        // Display commands
        System.out.println("Menu");
        System.out.println("1. For Creating New Customer ");
        System.out.println(" And saving it to the file");
        System.out.println("2. For Viewing File");
        System.out.println("3. For Exit\n");
 
        // Checking to erupt case sensitivity of input
        // character
        while (ch == 'y' || ch == 'Y') {
            // Asking user to enter the choice
            System.out.println("Enter Your Choice");
 
            // Scanner class object to take users choice
            Scanner sc = new Scanner(System.in);
 
            menuCh = sc.nextInt();
 
            // Switch case
            switch (menuCh) {
            case 1:
                createNewCustomerAndSave();
 
                // Break statement will immediately halt
                // further execution
                break;
            case 2:
                viewFile();
                break;
            case 3:
                exitStatus = 1;
                break;
 
            // Case if above all cases do not hit
            default:
                System.out.println("Wrong Choice");
                break;
            }
 
            // Checking exit status
            if (exitStatus == 1) {
                break;
            }
 
            // Asking from user
            System.out.println("Wanna Work More??? Yes/No");
 
            // skip /n ie newline
            ch = sc.next().charAt(0);
            ;
        }
    }
 
    // Method
    // To view the file
    public static void viewFile()
    {
 
        // Try block to check for exceptions
        try {
            System.out.println("Customers are : ");
 
            // Creating object of File class to get file
            // path
            File myObj = new File("CustomerData.txt");
 
            myObj.createNewFile();
 
            if (myObj.length() != 0) {
                Scanner myReader = new Scanner(myObj);
                myReader.useDelimiter(",");
 
                while (myReader.hasNextLine()) {
                    String str = myReader.nextLine();
 
                    // trim spaces
                    str = str.replaceAll("\\s", "");
                    String[] splitString = str.split(",");
                    String name = splitString[0];
                    long acc_No
                        = Long.valueOf(splitString[1]);
                    System.out.print("Name : " + name);
                    System.out.println(
                        " And account no is : " + acc_No);
                }
                myReader.close();
            }
        }
 
        // Catch block to handle the exceptions
        catch (Exception e) {
            System.out.println("An error occurred." + e);
            e.printStackTrace();
        }
    }
 
    // Method
    public static void createNewCustomerAndSave()
    {
        String name = null;
        String date = null;
 
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter Customer's Name");
        name = sc.nextLine();
        Customer c1 = new Customer(name);
        String dataToBeWriiten = null;
        try {
            File myObj = new File("CustomerData.txt");
            myObj.createNewFile();
            FileWriter myWriter1 = null;
            myWriter1
                = new FileWriter("CustomerData.txt", true);
            BufferedWriter myWriter
                = new BufferedWriter(myWriter1);
            long AccNo = c1.getAccNo();
            dataToBeWriiten
                = String.format("%30s ,%10d", name, AccNo);
            myWriter.write(dataToBeWriiten);
 
            myWriter.write(
                System.lineSeparator()); // to insert a new
                                         // line in file
            myWriter.close();
            System.out.println(
                "Successfully wrote to the file.\n");
        }
        catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}


 
 

Output: Two different output are obtained

 

  • Output 1: When we run for the first time
  • Output 2:: When the program is run again after the first time

 

Output 1: When we run for the first time

 

Menu
1. For Creating New Customer and saving it to the file
2. For Viewing File
3. For Exit

Enter Your Choice
1
Enter Customer's Name
Ramesh
Successfully wrote to the file.

Wanna Work More??? Yes/No
Y
Enter Your Choice
1
Enter Customer's Name
Rohan
Successfully wrote to the file.

Wanna Work More??? Yes/No
y
Enter Your Choice
2
Customers are : 
Name : Ramesh And account no is : 100
Name : Rohan And account no is : 101
Wanna Work More??? Yes/No
N

 

Also, after execution, “CustomerData.txt” was created & it contains the following contents :

 

Ramesh ,       100
Rohan ,       101

 

Explanation:

 

As you can see above 30 bytes have been reserved for the name (Eg: 24 white spaces & 6 bytes for Ramesh) and 10 bytes for the account no for each line written because we used String.format() for doing so.

 

When you read these lines one by one as a string, that string will contain white spaces also, to remove that white spaces we used the replaceAll() method to get a new string with no white spaces.

 

Eg: First line when read, str = " Ramesh, 100"

 

       When we use replaceAll(), str becomes

 

str = “Ramesh,100”

 

The string has no white spaces now has comma-separated values. In order to fetch those values individually, we used split() method & fetched the individual values & printed them.

 

Eg : After splitting the str according to ","  in our example we will had:

splitString[0] = Ramesh & splitString[1] = 100

 

So, the output was printed according to these split values

 

Output 2: When the program is run again after the first time

 

Menu
1. For Creating New Customer 
And saving it to the file
2. For Viewing File
3. For Exit

Enter Your Choice
1
Enter Customer's Name
Chetan
Successfully wrote to the file.

Wanna Work More??? Yes/No
y
Enter Your Choice
2
Customers are : 
Name : Ramesh And account no is : 100
Name : Rohan And account no is : 101
Name : Chetan And account no is : 100
Wanna Work More??? Yes/No
N

 

Output Explanation:

 

Now, before executing for the second time, you were already having the file “CustomerData.txt”’ that contains 2 lines of data.

 

Ramesh ,       100
Rohan ,       101

 

When you write the data in the append mode, the new data get to write after the data that was already there in the file. So the file “CustomerData.txt” would appear as shown below:

 

Ramesh ,       100
Rohan ,       101
Chetan ,       100

 

The file is then read in the same way as earlier & in the same way, all the contents of the file are read line by line, white spaces are removed & splitting is done & finally split data is printed.

 

RELATED ARTICLES

Most Popular

Recent Comments