Monday 11 March 2013

read File in Java using BufferedReader, Scanner, Files with Encoding support and FileReader

Leave a Comment

While working with files in Java, we need to read them. Earlier, I wrote about java property files and here I am providing different ways through which we can read a file in java.
java.nio.file.Files: If you want to read all the contents of a file into byte array or read all lines to a list, we can use Files class. Files class is introduced in Java 7 and it’s good if you want to load all the file contents. You should use this method only when you are working on small files and you need all the file contents in memory.
java.io.FileReader: You can use FileReader to get the BufferedReader and then read files line by line. FileReader doesn’t support encoding and works with the system default encoding, so it’s not very efficient way of reading file in java.
java.io.BufferedReader: BufferedReader is good if you want to read file line by line and process on them. It’s good for processing large file and it supports encoding also. BufferedReader is synchronized, so read operations on a BufferedReader can safely be done from multiple threads. BufferedReader default buffer size is 8KB.
java.util.Scanner: If you want to read file line by line or based on some java regular expression, Scanner is the class to use. Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods. Scanner is not synchronized and hence not thread safe.
Here is the example class showing how we can read file in java using Scanner, Files, BufferedReader with Encoding support and FileReader.
package com.harit;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Scanner;
 
public class JavaReadFile {
 
    public static void main(String[] args) throws IOException {
        String fileName = "/Users/pankaj/source.txt";
         
        //using Java 7 Files class to process small files, get complete file data
        readUsingFiles(fileName);
         
        //using Scanner class for large files, to read line by line
        readUsingScanner(fileName);
         
        //read using BufferedReader, to read line by line
        readUsingBufferedReader(fileName);
        readUsingBufferedReaderJava7(fileName, StandardCharsets.UTF_8);
        readUsingBufferedReader(fileName, StandardCharsets.UTF_8);
         
        //read using FileReader, no encoding support, not efficient
        readUsingFileReader(fileName);
    }
 
    private static void readUsingFileReader(String fileName) throws IOException {
        File file = new File(fileName);
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        String line;
        while((line = br.readLine()) != null){
            //process the line
            System.out.println(line);
        }
        br.close();
        fr.close();
         
    }
 
    private static void readUsingBufferedReader(String fileName, Charset cs) throws IOException {
        File file = new File(fileName);
        FileInputStream fis = new FileInputStream(file);
        InputStreamReader isr = new InputStreamReader(fis, cs);
        BufferedReader br = new BufferedReader(isr);
        String line;
        while((line = br.readLine()) != null){
            //process the line
            System.out.println(line);
        }
        br.close();
         
    }
 
    private static void readUsingBufferedReaderJava7(String fileName, Charset cs) throws IOException {
        Path path = Paths.get(fileName);
        BufferedReader br = Files.newBufferedReader(path, cs);
        String line;
        while((line = br.readLine()) != null){
            //process the line
            System.out.println(line);
        }
        br.close();
    }
 
    private static void readUsingBufferedReader(String fileName) throws IOException {
        File file = new File(fileName);
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        String line;
        while((line = br.readLine()) != null){
            //process the line
            System.out.println(line);
        }
        //close resources
        br.close();
        fr.close();
    }
 
    private static void readUsingScanner(String fileName) throws IOException {
        Path path = Paths.get(fileName);
        Scanner scanner = new Scanner(path);
        //read line by line
        while(scanner.hasNextLine()){
            //process each line
            String line = scanner.nextLine();
        }
    }
 
    private static void readUsingFiles(String fileName) throws IOException {
        Path path = Paths.get(fileName);
        //read file to byte array
        byte[] bytes = Files.readAllBytes(path);
        //read file to String list
        List allLines = Files.readAllLines(path, StandardCharsets.UTF_8);
    }
 
}

0 comments:

Post a Comment