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

We need to import the java.io.FileReader package before we can develop a 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:

In Java, there are various methods for creating and accessing text files. This is necessary when working with numerous programs. Java has various methods for reading plain text files, such as FileReader, BufferedReader, and Scanner. Each utility offers a unique feature, for example. Data is buffered by BufferedReader for quick reading, while parsing is provided by Scanner.

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 basic text scanner with regular expression parsing capabilities for strings and primitive kinds. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The various next methods can then be used to turn the resultant tokens into values of various sorts.

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:

Go through each line in a file. When all bytes have been read or an I/O error or other runtime exception is raised, this procedure makes sure the file is closed. Using the selected charset, the file’s bytes are decoded into characters.

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