To read data from the CSV file and write data to the TXT file, we have used the File I/O concept of Java. To convert CSV to TXT file, first, we need to read data line by line from CSV file and then we can convert line by line to a TXT file.
We have taken a sample CSV file to convert to TXT file. This file contains data of employees of different companies like Employee Name, Company Name, Designation and Salary.
See below data of CSV file to get details.
|1||SATYAJEET NAYAK||ABC||SOFTWARE ENGINEER||70000|
You can also use the below CSV file to convert to a TXT file in Java. To use this CSV file, just download this file from below and save it to your system. You can use this file location of your System as the path in the program.
How to convert CSV to TXT in Java?
You can convert CSV to TXT in Java by using the File IO concept. We can use FileReader and BufferedReader classes to read data from the CSV file and then FileWriter class to write the same data to a TXT file.
Let’s see the program now.
SL NO NAME COMPANY DESIGNATION SALARY 1 SATYAJEET NAYAK ABC SOFTWARE ENGINEER 70000 2 MACK MOHAN DEF HR 60000 3 JACK JOO GHI ADMIN 90000 4 MARLON MAC JKL CEO 256000 5 NOOR MAHOTA MNO TESTER 40000
- First, we have declared the file path of the CSV file as a String(String path = “C:/Satyajeet Nayak/Codingface/Demo.csv”;).
- We have use File, FileReader, and BufferedReader classes to read data from CSV files.
- We have used a demo TXT file(output.txt) to store employee data from the CSV file.
- Then, we have used a while loop(while ((line = br.readLine()) != null)) to check that file should not be empty. When the file is not empty, by using the write( ) method of Writer class we can write each line of CSV file to TXT file.
- Finally, the whole data of the CSV file will be converted to a TXT file.
Other Programmers Also Ask For:
- How to convert CSV file to TXT file in Java?
- How to convert CSV to TXT file?
- How to generate a TXT file from CSV file?