CSV stands for Comma-Separated Values. It is a document design utilized to keep information in an accounting page or dataset in a straightforward text structure. A delimiter is used to recognize and isolate information in comma-separated values. Show IntroductionThe CSV record design moves structured information between programs that locally work on incongruent organizations. PrerequisitesTo follow along, the reader should:
Table of contents
Creating a CSV fileMicrosoft Excel office
Notepad
Java String.split() technique 0, applied to break string around matches of the given standard articulation. In the code below, we imported 1. 1 reads the file line by line to the end.
The output of the code is as shown below:
Java scanner classThis is a class in the 3 bundle, used to get input from the user. It breaks information into tokens, utilizing the delimiter pattern. It is the most straightforward method to read input in Java code.We used the scanner class to read CSV files in Java in the code below:
The output is as shown below:
Using openCSV APIOpenCSV is an outsider API utilized to peruse different adaptations of the comma-separated document. It supports all basic Comma-separated operations. OpenCSV is used since Java does not provide native support to read Comma-Separated values. Important OpenCSV classes
Comma-separated values are read in two ways, mainly:
8The syntax for open CSV: 9Reading CSV files in JavaStep 1Create two folders in eclipse-workspace and name them 0 and 1. In the 1 folder, move the CSV files that you will use. In this case, we will use comma-separated and semicolon-separated files.Then in the 0 folder paste 4 and 5 jar files. If you don’t have them, download them by clicking opencsv5.5.2 and commonlangs3-3.1Step 2Open Eclipse, and create a Java project. Name the project as 6 and click next.Step 3Click 7 and select 8. Then select 9 and add jars from CSVDoc in the Eclipse-workspace folder. Then click finish.Step 4After that, create a Java class. Right-click on the project CSVOperation and select new, then select class. Step 5Name the class as 0 and click finish.Step 6Then copy the code sample beneath and paste. Run the program.
The output should resemble the one below:
You will note the absence of commas. This is because when using open CSV API, the commas are ignored. Let’s implement a program to read a CSV file not separated by commas. Instead, it’s separated with semi-colons(;). The CSV file that we are going to read is shown below: Copy the program below and paste and run it.
The output is shown below:
In the output above, you will note the presence of semi-colon separators. This is because OpenCSV ignores commas, but other separators are recognized. ConclusionThis article focused on various techniques to create CSV files in Java. We also learned different methods of reading Comma Separated Values (CSV) in Java. Finally, we used open CSV API to read CSV files. |