Different Ways of Reading a text file in Java

There are various approaches to composing and perusing a text document. this is needed while managing numerous applications. There are multiple ways of perusing a plain text record in Java for example you can utilize FileReader, BufferedReader, or Scanner to peruse a text document. Each utility gives something exceptional for example BufferedReader gives buffering of information to quick perusing, and Scanner gives parsing capacity.

Strategies:

  • Utilizing BufferedReader class
  • Utilizing Scanner class
  • Utilizing File Reader class
  • Perusing the entire document in a List
  • Peruse a text document as String

We can likewise utilize both BufferReader and Scanner to peruse a text document line by line in Java. Then, at that point, Java SE 8 presents another Stream class java.util.stream.Stream which gives an apathetic and more productive method for perusing a document.

Tip Note: Practices of composing great code like flushing/shutting streams, Exception-Handling and so on, have been stayed away from for better comprehension of codes by fledglings too.

Allow us to examine every one of the above techniques to a more profound profundity and in particular by carrying out them by means of a perfect java program.

1: Using BufferedReader class

This strategy peruses text from a person input stream. It cradles for productive perusing of characters, exhibits, and lines. The cradle size might be indicated, or the default size might be utilized. The default is huge enough for most purposes. As a general rule, each read demand made of a Reader makes a relating read demand be made of the fundamental person or byte stream. It is in this way fitting to fold a BufferedReader over any Reader whose read() tasks might be exorbitant, for example, FileReaders and InputStreamReaders as displayed underneath as follows:

BufferedReader in = new BufferedReader(Reader in, int size);

Example:

// Java Program to illustrate Reading from FileReader
// using BufferedReader Class
// Importing input output classes
import java.io.*;
// Main class
public class GFG {
    // main driver method
    public static void main(String[] args) throws Exception
    {
        // File path is passed as parameter
        File file = new File(
            "C:\\Users\\pankaj\\Desktop\\test.txt");
        // Note:  Double backquote is to avoid compiler
        // interpret words
        // like \test as \t (ie. as a escape sequence)
        // Creating an object of BufferedReader class
        BufferedReader br
            = new BufferedReader(new FileReader(file));
        // Declaring a string variable
        String st;
        // Condition holds true till
        // there is character in a string
        while ((st = br.readLine()) != null)
            // Print the string
            System.out.println(st);
    }
}

Output:

If you want to code refer to eevibes

2: Using FileReader class

Accommodation class for perusing character documents. The constructors of this class accept that the default character encoding and the default byte-support size are proper.

Constructors characterized in this class are as per the following:

  • FileReader(File document): Creates another FileReader, given the File to peruse from
  • FileReader(FileDescriptor fd): Creates another FileReader, given the FileDescriptor to peruse from
  • FileReader(String fileName): Creates another FileReader, given the name of the document to peruse from

Example:

// Java Program to Illustrate reading from
// FileReader using FileReader class
// Importing input output classes
import java.io.*;
// Main class
// ReadingFromFile
public class GFG {
    // Main driver method
    public static void main(String[] args) throws Exception
    {
        // Passing the path to the file as a parameter
        FileReader fr = new FileReader(
            "C:\\Users\\pankaj\\Desktop\\test.txt");
        // Declaring loop variable
        int i;
        // Holds true till there is nothing to read
        while ((i = fr.read()) != -1)
            // Print all the content of a file
            System.out.print((char)i);
    }
}

Output:

If you want to code refer to eevibes

3: Using Scanner class

A basic text scanner that can parse crude sorts and strings utilizing customary articulations. A Scanner breaks its contribution to tokens utilizing a delimiter design, which naturally matches whitespace. The subsequent tokens may then be changed over into upsides of various sorts utilizing the different next strategies.

Example 1: With using loops

// Java Program to illustrate
// 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\\pankaj\\Desktop\\test.txt");
    Scanner sc = new Scanner(file);
    while (sc.hasNextLine())
      System.out.println(sc.nextLine());
  }
}

Output:

If you want to code refer to eevibes

Example 2: Without using loops

// Java Program to illustrate reading from FileReader
// using Scanner Class reading entire File
// without using loop
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadingEntireFileWithoutLoop
{
  public static void main(String[] args)
                        throws FileNotFoundException
  {
    File file = new File("C:\\Users\\pankaj\\Desktop\\test.txt");
    Scanner sc = new Scanner(file);
    // we just need to use \\Z as delimiter
    sc.useDelimiter("\\Z");
    System.out.println(sc.next());
  }
}

Output:

If you want to code refer to eevibes

4: Reading the entire record in a List

Peruse all lines from a record. This technique guarantees that the record is shut when all bytes have been perused or an I/O blunder, or other runtime exemption, is tossed. Bytes from the record are decoded into characters utilizing the predetermined charset.

Syntax:

public static List readAllLines(Path path,Charset cs)throws IOException

This method recognizes the following as line terminators:

\u000D followed by \u000A, CARRIAGE RETURN followed by LINE FEED
\u000A, LINE FEED
\u000D, CARRIAGE RETURN

Example

// Java program to illustrate reading data from file
// using nio.File
import java.util.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.io.*;
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\\pankaj\\Desktop\\test.java");
    Iterator<String> itr = l.iterator();
    while (itr.hasNext())
      System.out.println(itr.next());
  }
}

Output:

If you want to code refer to eevibes

5: Read a text file as String

Example

// Java Program to illustrate
// 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\\pankaj\\Desktop\\test.java");
    System.out.println(data);
  }
}

Output:

If you want to code refer to eevibes

Also ReadHow to Install Minecraft on Linux?

Leave a Reply

Your email address will not be published.