Java Read File

What is File Reader?

The FileReader class of the java.io package can be used to read data from files. It extends the InputSreamReader class. Before you learn about  File Reader, you have to know about Java File.

Create a FileReader

In order to create a file reader, we must import the java.io.FileReader package first. Once we import the package, here is how we can create the file reader.

1. Using the name of the file

Example:

  •  Create a file using Java code
  • Declare an object>instantiate the object>call create file method
File createFile01=new File("C:\\Java\\myJavaFile.txt");
createFile01.createNewFile();

How to Read File:

Step 1: Find the file and set the handle on it

FileReader f;
        f=null;
        try {
            f=new FileReader("C:\\Java\\readFile.txt");
        }
        catch(FileNotFoundException e) {
            System.out.println("File not found");
        }

Step 2: Store file content in RAM(Buffer)

BufferedReader b;
b= new BufferedReader(f);

Step 3: Read line by line from RAM(Buffer)

try {
   String currentLine=b.readLine();
   while(currentLine!=null) {
       System.out.println(currentLine);
       currentLine=b.readLine();
   }
}//try

catch(IOException e) {
 e.printStackTrace();
 System.out.println("Can not read file");
}//catch

Types of FileReader:

There are multiple ways of writing and reading a text file in Java. this is required while dealing with many applications. There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader, or Scanner to read a text file. Every utility provides something special e.g. BufferedReader provides buffering of data for fast reading, and Scanner provides parsing ability.

File Read using Buffer Reader:

This method reads text from a character-input stream. It does buffer for efficient reading of characters, arrays, and lines.

Example 1:

public class fileReader{
  public static void main (String[] args){

// C:\Java\createNewFile.txt
        //How to read a file 
        // Step 1: Find the file and set handle on it
        FileReader f;
        f=null;
        try {
            f=new FileReader("C:\\Java\\readFile.txt");
        }
        catch(FileNotFoundException e) {
            System.out.println("File not found");
        }
        
        // //Step 2: Store file content in RAM(Buffer)
        BufferedReader b;
        b= new BufferedReader(f);
        
        ////Step 3: Read line by line from RAM(Buffer)
        try {
            String currentLine=b.readLine();
            while(currentLine!=null) {
                System.out.println(currentLine);
                currentLine=b.readLine();
            }
            //else
                //System.out.println("Blank file");
        }
            catch(IOException e) {
                e.printStackTrace();
                System.out.println("Can not read file");
            }
   }//main
 }//class

Output:

File Read Completed

Example with user.dir:

 

public class fileReader{
  public static void main (String[] args){

    try {
        // Get the current working directory (user.dir)
        String currentDir = System.getProperty("user.dir");

        // File path of the file to read
        String filePath = currentDir + "/example.txt";

        // Create a FileReader and BufferedReader to read the file
        FileReader fileReader = new FileReader(filePath);
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        // Read the file line by line
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }

        // Close the resources
        bufferedReader.close();
        fileReader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
  }//main
}//class

Text File read with user.dir complete

File Read using scanner class:

A simple text scanner that can parse primitive types and strings using regular expressions. A 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.

Example:

// Using Loop
// reading from Text File
// using Scanner Class
import java.io.File;
import java.util.Scanner;
public class ReadFromFileUsingScanner {
    public static void main(String[] args) throws Exception
    {
        // pass the path to the file as a parameter
        File file = new File(
            "C:\\Users\\sarker\\Desktop\\testfile.txt");
        Scanner sc = new Scanner(file);

        while (sc.hasNextLine())
            System.out.println(sc.nextLine());
    }
}

Output:

File Read complete using scanner class

 

Reading whole file from list:

Read all lines from a file. This method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown. Bytes from the file are decoded into characters using the specified charset.

Example:

// Java program to illustrate reading data from file
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
public class ReadFileIntoList {
    public static List<String>
    readFileInList(String fileName){
    
        List<String> lines = Collections.emptyList();
        try {
            lines = Files.readAllLines(
                Paths.get(fileName),
                StandardCharsets.UTF_8);
        }
 
        catch (IOException e) {
 
            // do something
            e.printStackTrace();
        }
        return lines;
    }
    public static void main(String[] args)
    {
        List l = readFileInList(
            "C:\\Users\\java\\Desktop\\test.java");
 
        Iterator<String> itr = l.iterator();
        while (itr.hasNext())
            System.out.println(itr.next());
    }
}

Output:

The whole Text File read complete

 

Reading Text File as String:

Example:

// reading from text file
// as string in Java
package io;
 
import java.nio.file.*;
;
 
public class ReadTextAsString {
 
    public static String readFileAsString(String fileName)
        throws Exception
    {
        String data = "";
        data = new String(
            Files.readAllBytes(Paths.get(fileName)));
        return data;
    }
 
    public static void main(String[] args) throws Exception
    {
        String data = readFileAsString(
            "C:\\Users\\java\\workspace\\test.java");
        System.out.println(data);
    }
}

Output:

Text File read complete

 

 

Visited 1 times, 1 visit(s) today

Comments are closed.

Close