How To Read File Line By Line In Java

Java offers multiple efficient techniques for achieving this objective. In the following segment, we will delve into diverse strategies for sequentially reading files in Java, encompassing both conventional and contemporary methodologies.

Two methods to read a file line by line are:

  • Utilizing the BufferedReader Class
  • Leveraging the Scanner Class
  • Using BufferedReader Class

The Java BufferedReader class is a widely used and straightforward approach for reading a file line by line in Java. This class is part of the java.io package. The BufferedReader class in Java offers the readLine method specifically for reading a file line by line, with the following method signature:

Example

public String readLine() throws IOException

The function reads a single line of text and returns a string that holds the line's content. The line should end with either a line feed ("\n") or carriage return ("\r").

Example

try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {

    String line;

    while ((line = reader.readLine()) != null) {

        // Process each line

    }

} catch (IOException e) {

    e.printStackTrace();

}

This method is simple and effective for processing extensive files by storing input from the file, which decreases the amount of I/O operations required.

Java Program Read File Line by Line

In this instance, the FileReader class is utilized to read the Demo.txt file. By using the readLine function from the BufferedReader class, the file is read line by line and each line is added to a StringBuffer with a linefeed. Subsequently, the content stored in the StringBuffer is displayed on the console.

ReadLineByLineExample1.java

Example

import java.io.*;

public class ReadLineByLineExample1

{

public static void main(String args[])

{

try

{

File file=new File("Demo.txt");    //creates a new file instance

FileReader fr=new FileReader(file);   //reads the file

BufferedReader br=new BufferedReader(fr);  //creates a buffering character input stream

StringBuffer sb=new StringBuffer();    //constructs a string buffer with no characters

String line;

while((line=br.readLine())!=null)

{

sb.append(line);      //appends line to string buffer

sb.append("\n");     //line feed 

}

fr.close();    //closes the stream and release the resources

System.out.println("Contents of File: ");

System.out.println(sb.toString());   //returns a string that textually represents the object

}

catch(IOException e)

{

e.printStackTrace();

}

}

}

Output:

Using the Scanner Class

The Java Scanner class offers additional utility functions compared to the BufferedReader class. It includes the nextLine method for reading a file's content line by line, which returns a String similar to the readLine method. Moreover, the Scanner class supports reading files from an InputStream.

Example

try (Scanner scanner = new Scanner(new File("file.txt"))) {

    while (scanner.hasNextLine()) {

        String line = scanner.nextLine();

        // Process each line

    }

} catch (FileNotFoundException e) {

    e.printStackTrace();

}

The Scanner class provides flexibility in processing various kinds of input, although it might not be as optimal as BufferedReader when handling extensive files because of its internal buffering system.

Java Program Read File Line by Line

ReadLineByLineExample2.java

Example

import java.io.*;

import java.util.Scanner;

public class ReadLineByLineExample2

{

public static void main(String args[])

{

try

{

//the file to be opened for reading

FileInputStream fis=new FileInputStream("Demo.txt");	 

Scanner sc=new Scanner(fis);	//file to be scanned

//returns true if there is another line to read

while(sc.hasNextLine())

{

System.out.println(sc.nextLine());		//returns the line that was skipped

}

sc.close();		//closes the scanner

}

catch(IOException e)

{

e.printStackTrace();

}

}

}

Output:

Best Practices and Considerations

When reading files line by line in Java, it is essential to consider various factors to ensure efficiency, reliability, and maintainability.

  • Exception Handling: Always handle IOExceptions gracefully when reading files to prevent unexpected failures. Use try-with-resources statement (introduced in Java 7) to ensure proper resource management and automatic closure of resources.
  • Encoding: Specify the character encoding when reading files, especially if dealing with non-ASCII characters. The FileReader constructor and Files.lines method allow specifying the charset as an optional parameter.
  • Performance: Choose the appropriate method based on the size and nature of the file. BufferedReader is ideal for large files due to its efficient buffering, while Files.lines and Scanner are suitable for smaller files and stream-based operations.
  • Memory Consumption: Be mindful of memory consumption, especially when dealing with large files. BufferedReader and Files.lines read files efficiently in chunks, minimizing memory usage. Avoid loading the entire file into memory if unnecessary.
  • Error Handling: Implement robust error handling and logging mechanisms to handle file-related errors gracefully. Consider scenarios like file not found, permission issues, or unexpected file formats.
  • Conclusion

Engaging in the process of reading files line by line is a fundamental practice in Java development, playing a crucial role in a wide array of activities such as data manipulation and file interpretation. Proficiency in employing various strategies for file reading allows programmers to effectively manage a variety of file processing needs, ensuring both the dependability and efficiency of their code. Whether utilizing classic methods like BufferedReader and FileReader or contemporary techniques such as Files.lines and Scanner, having a deep comprehension of the intricacies and recommended approaches to file reading in Java is indispensable for constructing resilient and high-performing software solutions.

Input Required

This code uses input(). Please provide values below: