Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Thursday, October 26, 2017

4 Different ways of Reading a text file in Java (CSV Files)

In this post, We will learn very basic program How to read a file in Java. Very useful scenario which is prominently used in our real time projects.
How to read csv file in java. This is a common use case.

java.io package has utility classes for reading and writing files.

We can do reading a file in java 4 ways.

1) Using BufferedReader
2) Using JDK 7 try-with-resources
3) Using Files.readAllBytes
4) Using Files.readAllLines

4 Ways How to read a file in Java, CSV Example Programs

First, Create a csv file with the following data in your computer(File name : employee.csv).

100,Jhon,20
101,Cena,24
102,Mike,19

 

1) Using BufferedReader:


This is very classic method to read a file using BufferedReader, FileReader. We will read the csv file using BufferedReader api and prints values of Id, Name, Age from csv file.

package com.adeepdrive.arraylist;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadingFile {

    public static void main(String[] args) {
        // file name
        String FILE_NAME = "D:\\adeepdrive\\employee.csv";

        BufferedReader br = null;
        FileReader fr = null;

        try {

            fr = new FileReader(FILE_NAME);
            br = new BufferedReader(fr);

            String currentLine;

            while ((currentLine = br.readLine()) != null) {
                String[] values = currentLine.split(",");
                System.out.println("Id: " + values[0] + ", Name: " + values[1] + ", Age: " + values[2]);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {

                if (br != null)
                    br.close();

                if (fr != null)
                    fr.close();

            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }
}


Output:

Id: 100, Name: Jhon, Age: 20
Id: 101, Name: Cena, Age: 24
Id: 102, Name: Mike, Age: 19

FILE_NAME holds file name and location of csv file. This can be flat file or csv file.
BufferedReader class has a method to read the file content line by line using readLine() method.
File reading operation throws IOException. So, we have put the code in try and catch block.

How to Write comment in Java

2) Using JDK 7 try-with-resources:


The same above program is rewritten in java 7 using try with resources concept which closes the  br and fr automatically implicitly.

       
 String FILE_NAME = "D:\\adeepdrive\\employee.csv";
        try (BufferedReader br = new BufferedReader(new FileReader(FILE_NAME))) {

            String currentLine;

            while ((currentLine = br.readLine()) != null) {
                String[] values = currentLine.split(",");
                System.out.println("Id: " + values[0] + ", Name: " + values[1] + ", Age: " + values[2]);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

Output:

Id: 100, Name: Jhon, Age: 20
Id: 101, Name: Cena, Age: 24
Id: 102, Name: Mike, Age: 19

3) Using Files.readAllBytes

Files is a class that consists exclusively of static methods that operate on files, directories, or other types of files.
Files has a static method readAllBytes(Path path). This method reads entire file content at once and stores in String.

Static in Java.

package com.adeepdrive.arraylist;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ReadingFiles {

    public static void main(String[] args) throws IOException {
        // file name
        String FILE_NAME = "D:\\adeepdrive\\employee.csv";
        String content = new String(Files.readAllBytes(Paths.get(FILE_NAME)));
        System.out.println("CSV File Content : ");
        System.out.println(content);
    }
}

Output:

CSV File Content :
100,Jhon,20
101,Cena,24
102,Mike,19

4) Using Files.readAllLines:


Method readAllLines(Path path) returns list which stores all lines. Reading file in Java.

   
 String FILE_NAME = "D:\\adeepdrive\\employee.csv";
        List<String> content = Files.readAllLines(Paths.get(FILE_NAME));
        System.out.println("CSV File Content : ");
        for (String line : content) {
            String[] values = line.split(",");
            System.out.println("Id: " + values[0] + ", Name: " + values[1] + ", Age: " + values[2]);
        }
        

Output:

CSV File Content :
Id: 100, Name: Jhon, Age: 20
Id: 101, Name: Cena, Age: 24
Id: 102, Name: Mike, Age: 19


No comments:

Post a Comment

Please do not add any spam links in the comments section.