How to Read Write Object's Data in CSV Format Using Notepad in Java?
Last Updated :
10 Nov, 2022
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
- Open a file (using the fully qualified name of the file) using FileReader & BufferedReader.
- Use the split() method to split the data that was read in comma-separated format.
- Read the individual split values.
- Print the values.
- Close both the Readers.
B. File Writing
- Create any class Object & assign values to its data members.
- Create & open a file (using the fully qualified name of the file) in append mode using FileWriter & BufferedWriter.
- 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)
- Write the formatted string to the file using write() method of BufferedWriter Class.
- 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.
Similar Reads
How to Read and Write Files Using the New I/O (NIO.2) API in Java?
In this article, we will learn how to read and write files using the new I/O (NIO) API in Java. For this first, we need to import the file from the NIO package in Java. This NIO.2 is introduced from the Java 7 version. This provides a more efficient way of handling input and output operations compar
3 min read
How to Format the Text in a Word Document using Java?
Apache POI is a project run by the Apache Software Foundation, and previously a sub-project of the Jakarta Project provides pure Java libraries for reading and writing files in Microsoft Office formats, such as Word, PowerPoint, and Excel. First do install Apache in order to import modules as per th
3 min read
How to Write Data into Excel Sheet using Java?
Handling files is an important part of any programming language. Java provides various in-built methods for creating, reading, updating, and deleting files. These methods are provided by the File class which is present in the java.io package. To perform file operations, Java uses the stream class. T
3 min read
How to Read and Write JSON Files in Java?
JSON (JavaScript Object Notation) is simple but poweÂrful.. It helps the server and the client to share information. Applications like Java use special tools, or libraries, that reÂad JSON. In Java, some libraries make it easy to read and write JSON files. One popular library is Jackson.In this art
4 min read
How to Set Direction to the Text in Cell using Java?
Apache POI is an open-source library by Apache which can be used to create, modify and display files MS office file in Java. It provides classes and methods to do so. This API provides various components such as POIFS (Poor Obfuscation Implementation File System), HSSF (Horrible Spreadsheet Format),
3 min read
How to Create Different Types of Cells in a Spreadsheet using Java?
Apache POI is an API which was provided by Apache Foundation and is used to set the various type of values to the cell. The overloading function setCellValue() of Apache POI is used to set the value type of the cell. Maven is a powerful project management tool that is based on POM (project object mo
4 min read
Java Program to Create an Object for Class and Assign Value in the Object Using Constructor
Java is one of the most popular programming languages. It is an object-oriented programming language which means that we can create classes, objects, and many more. It also supports inheritance, polymorphism, encapsulation, and many more. It is used in all applications starting from mobile applicati
3 min read
How to Read and Write XML Files in Java?
XML is defined as the Extensible Markup Language, and it is mostly used as a format for storing and exchanging data between systems. To read and write XML files, Java programming offers several easily implementable libraries. The most widely used library is the built-in JAXP (Java API for XML proces
5 min read
How to Read and Write Binary Files in Java?
The Binary files contain data in a format that is not human-readable. To make them suitable for storing complex data structures efficiently, in Java, we can read from and write to binary files using the Input and Output Streams.In this article, we will learn and see the code implementation to read a
2 min read
How to Apply Different Styles to a Cell in a Spreadsheet using Java?
Apache POI is a powerful API that enables the user to create, manipulate, and display various file formats based on Microsoft Office using java programs. Using POI, one should be able to perform create, modify, and display/read operations on the following file formats. For Example, Java doesnât prov
6 min read