close
The Wayback Machine - https://web.archive.org/web/20240828234553/https://www.geeksforgeeks.org/different-ways-reading-text-file-java/
Open In App

Different ways of Reading a text file in Java

Last Updated : 20 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Methods:

  1. Using BufferedReader class
  2. Using Scanner class
  3. Using File Reader class
  4. Reading the whole file in a List
  5. Read a text file as String

We can also use both BufferReader and Scanner to read a text file line by line in Java. Then Java SE 8 introduces another Stream class java.util.stream.Stream which provides a lazy and more efficient way to read a file.

Tip Note: Practices of writing good code like flushing/closing streams, Exception-Handling etc, have been avoided for better understanding of codes by beginners as well.

Let us discuss each of the above methods to a deeper depth and most importantly by implementing them via a clean java program. 

1. BufferedReader class for Reading text file

This method reads text from a character-input stream. It does buffer for efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes. In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders as shown below as follows:

Syntax

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

Example

Java




// 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 GeeksforGeeks

2. FileReader class for Reading text file

Convenience class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. 

Constructors defined in this class are as follows:

  1. FileReader(File file): Creates a new FileReader, given the File to read from
  2. FileReader(FileDescriptor fd): Creates a new FileReader, given the FileDescriptor to read from
  3. FileReader(String fileName): Creates a new FileReader, given the name of the file to read from

Example

Java




// 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 GeeksforGeeks

3. Scanner class for reading text file

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 1: With using loops

Java




// 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 GeeksforGeeks

Example 2: Without using loops

Java




// 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 GeeksforGeeks

4. Reading the whole file in a 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. 

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




// Java program to illustrate reading data from file
// using nio.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\\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 GeeksforGeeks

5. Read a text file as String

Example

Java




// 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 GeeksforGeeks



Previous Article
Next Article

Similar Reads

Reading a CSV file in Java using OpenCSV
A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in column by column, and split it by a separator (e.g normally it is a comma “, ”). OpenCSV is a CSV parser library for Java. OpenCSV supports all the basic CSV-type operations you are want to do. Java 7 is currently the minimum supported version for OpenCSV. Java lang
7 min read
Reading and Writing Properties File in Java
The property file is a file we use in the Java Programming language to keep the configuration parameters. These files we called Resource Bundle because it is a bundle of resources that we are going to use in the application. What are the configuration parameters? Configuration parameters are the parameters that you use at the time of configuring yo
4 min read
Reading and Writing Data to Excel File in Java using Apache POI
In Java, reading an Excel file is not similar to reading a Word file because of cells in an Excel file. JDK does not provide a direct API to read data from Excel files for which we have to toggle to a third-party library that is Apache POI. Apache POI is an open-source java library designed for reading and writing Microsoft documents in order to cr
5 min read
How to Create Different Packages For Different Classes in Java?
Let us first know what is a class and package in Java. Class in java is a model for creating objects. It means that the properties and actions of the objects are written in class. Properties are represented by variables and actions of the objects are represented by methods. So, a class contains variables and methods. The same variables are also ava
6 min read
Different ways for String to Integer Conversions in Java
Given a String in Java, the task is to convert this String into Integer. Examples: Input: str = "1234" Output: 1234 Input: str = "456" Output: 456 Convert using Integer.parseInt(String) The Integer class has a static method that returns an integer object representing the specified String parameter. Syntax : public static int parseInt(String str) th
2 min read
Different Ways to Remove all the Digits from String in Java
Given alphanumeric string str, the task is to write a Java program to remove all the digit from this string and prints the modified string. Examples: Input: str = “GeeksForGeeks123”Output: GeeksForGeeksExplanation: The given string contains digits 1, 2, and 3. We remove all the digit and prints the modified string. Input: str = “12Java”Output: Java
3 min read
Different Ways to Generate String by using Characters and Numbers in Java
Given a number num and String str, the task is to generate the new String by extracting the character from the string by using the index value of numbers. Examples: Input: str = “GeeksforGeeks” num = 858 Output: GfG Explanation: The 8th, 5th, and 8th position of the characters are extracting from the given string and generate a new string. Input: s
3 min read
Different Ways To Check Java Version In Windows
Java is a programming language that is platform-independent, popular, simple, secure, and statically typed. Before discussing let's clear Java language needs a runtime platform so before going ahead let's clear how java is present on the machine. Java language comprises three components mainly: Java Development KitJava Runtime EnvironmentJava Virtu
3 min read
Different Ways to Achieve Pass By Reference in Java
There are two types of parameters one is Formal parameters and the second is Actual Parameters. Formal parameters are those parameters that are defined during function definition and Actual parameters are those which are passed during the function call in other Function. Showcasing the formal and actual parameters through code: Java Code // Java pr
5 min read
Different Ways To Declare And Initialize 2-D Array in Java
An array with more than one dimension is known as a multi-dimensional array. The most commonly used multi-dimensional arrays are 2-D and 3-D arrays. We can say that any higher dimensional array is basically an array of arrays. A very common example of a 2D Array is Chess Board. A chessboard is a grid containing 64 1x1 square boxes. You can similarl
8 min read
Different Ways to Prevent Method Overriding in Java
Inheritance is a substantial rule of any Object-Oriented Programming (OOP) language but still, there are ways to prevent method overriding in child classes which are as follows: Methods: Using a static methodUsing private access modifierUsing default access modifierUsing the final keyword method Method 1: Using a static method This is the first way
5 min read
Different Ways to Create the Instances of Wrapper Classes in Java
Wrapper Class a class whose object wraps or contains primitive data types. When we create an object to a wrapper class, it contains a field and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object. Methods: We can use two ways to construct the instance of the Wrapper Classes Usi
5 min read
Different Ways to Copy Files in Java
There are mainly 3 ways to copy files using java language. They are as given below: Using File Stream (Naive method)Using FileChannel ClassUsing Files class. Note: There are many other methods like Apache Commons IO FileUtils but we are solely discussing copying files using java classes. Method 1: Using File Stream (Naive method) This is a naive me
5 min read
Different Ways to Capture Java Heap Dumps
Head dump is a snapshot of all the objects that are in memory in the JVM at a certain moment. They are very useful to troubleshoot memory-leak problems and optimize memory usage in Java applications. Head dumps are usually stored in Binary format 'hprof' files. We can open and analyze these files using tolls like 'jhat' or 'JVisualVM'. Also, for Ec
6 min read
Different Ways to Set a Classpath in Java
Java Virtual Machine(JVM) uses classpath to locate the class files to execute the code. If your classpath is not set and the class file is not present in the same directory as your java file, then JVM will be unable to find the required class file, and it will throw an error (java.lang.ClassNotFoundException). Ways to Set a Classpath There are five
3 min read
Different Ways to Run Applet in Java
Applets are tiny Java programs that can be installed and run automatically as part of a web page. They can be viewed on an Internet server, transmitted over the Internet, and installed and run automatically as part of a web document or desktop application. Note:Java applet is deprecated, which means it's no longer recommended for use and may be rem
3 min read
Different Ways of Array Sorting Techniques in Java with JUnit
Accounting software /medical software / educational software etc. requires sorted data to be given for some analysis and also to prepare bar charts, pie charts, bar graphs, etc., In this tutorial let us see how to get sorted data in a java way. We need to know about the comparable interface and comparator interface also before moving further. Compa
6 min read
Different Ways to Collect Garbage in Java HotSpot JVM
JDKs come with different JVM implementations (Oracle HotSpot, Eclipse OpenJ9, GraalVM, Jikes RVM, Codename One), and different garbage collector implementations with different tuning options (Serial, Parallel, CMS, G1, Z, Shenandoah). In this article, we will know more about the Garbage Collector, how it works, and the various types of GC available
7 min read
Java Convert int to String | Different Ways Of Conversion
Converting Integers to Strings involves using the Integer classes toString() or String.valueOf() for direct conversion. String.format() is another method offering flexible formatting options. Using StringBuilder or StringBuffer for appending integer values as strings is efficient for extensive string manipulation. We generally counter with such con
9 min read
Different ways of Method Overloading in Java
If a class has multiple methods having same name but parameters of the method should be different is known as Method Overloading.If we have to perform only one operation, having same name of the methods increases the readability of the program.Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you
7 min read
Different Ways to Print Exception Messages in Java
In Java, there are three methods to print exception information. All of them are present in the Throwable class. Since Throwable is the base class for all exceptions and errors, we can use these three methods on any exception object. Methods to Print Exceptions in Java There are three methods to print exception messages in Java. These are: 1. java.
2 min read
Different ways to create objects in Java
There are several ways by which we can create objects of a class in java as we all know a class provides the blueprint for objects, you create an object from a class. This concept is under-rated and sometimes proves to be beneficial as this concept is bypassed by many programmers and sometimes even do ask from interview perceptive. Methods: There a
6 min read
Sort a String in Java (2 different ways)
The string class doesn't have any method that directly sorts a string, but we can sort a string by applying other methods one after another. The string is a sequence of characters. In java, objects of String are immutable which means a constant and cannot be changed once created. Creating a String There are two ways to create a string in Java: Stri
6 min read
Java - Reading From a URL using URLConnection Class
URLConnection is an abstract class whose subclasses form the link between the user application and any resource on the web. We can use it to read/write from/to any resource referenced by a URL object. There are mainly two subclasses that extend the URLConnection class HttpURLConnection: If we are connecting to any URL which uses "http" as its proto
5 min read
How to Create and Modify Properties File Form Java Program in Text and XML Format?
Properties file are a text-oriented key value a pair of contents present in a Java project with .properties extension. Line by line, the key-value pair of contents are present, and they are usually prepared by means of notepad, Wordpad, EditPlus, etc., Properties files are usually helpful to store important sensitive information and in this article
5 min read
Java Program to Count the Number of Lines, Words, Characters, and Paragraphs in a Text File
Counting the number of characters is essential because almost all the text boxes that rely on user input have certain limitations on the number of characters inserted. For example, the character limit on a Facebook post is 63206 characters. Whereas for a tweet on Twitter, the character limit is 140 characters, and the character limit is 80 per post
3 min read
Java program to delete certain text from a file
Prerequisite : PrintWriter , BufferedReader Given two files input.txt and delete.txt. Our Task is to perform file extraction(Input-Delete) and save the output in file say output.txt Example : Naive Algorithm : 1. Create PrintWriter object for output.txt 2. Open BufferedReader for input.txt 3. Run a loop for each line of input.txt 3.1 flag = false 3
3 min read
Java program to delete duplicate lines in text file
Prerequisite : PrintWriter , BufferedReader Given a file input.txt . Our Task is to remove duplicate lines from it and save the output in file say output.txt Naive Algorithm : 1. Create PrintWriter object for output.txt 2. Open BufferedReader for input.txt 3. Run a loop for each line of input.txt 3.1 flag = false 3.2 Open BufferedReader for output.
3 min read
How to Execute SQL File with Java using File and IO Streams?
In many cases, we often find the need to execute SQL commands on a database using JDBC to load raw data. While there are command-line or GUI interfaces provided by the database vendor, sometimes we may need to manage the database command execution using external software. In this article, we will learn how to execute an SQL file containing thousand
5 min read
How to Convert a Kotlin Source File to a Java Source File in Android?
We use Android Studio to translate our Java code into Kotlin while transitioning from Java to Kotlin. But what if we need to convert a Kotlin file to its Java equivalent? We'll examine how to convert a Kotlin source file to a Java source file in this blog. Let's get this party started. Because of its interoperability with Java, Kotlin grew at an ex
2 min read
Article Tags :
Practice Tags :