Reading files effectively in Java

prachi sharma
Posted on 4th Apr 2024 5:04 PM | 10 min Read | 60 min Implementation


#read-file #scanner #buffered-reader

Why do we need to read text files using Java?


The need to read a text file in Java arises from the necessity to interact with external data sources. Text files serve as a common way to store information outside of a Java program. By reading text files, Java programs can access data such as configuration settings, user input, logs, or any other textual information & process data stored in a text file for further usage & analysis.


Use-case :

imagine you have a Java program that needs to load user preferences from a file, such as a configuration file. Instead of hardcoding these preferences into the program, you can store them in a text file. By reading this file, the Java program can adjust its behavior according to the user's preferences without needing to modify the code.


1 - If file having ascii code values like normal english words

2 - If file having unicode characters like (Hindi, Japanese, Chinese etc characters)




In summary, the need to read text files in Java enables programs to interact with external data sources, providing flexibility, and the ability to handle diverse types of textual information.


A brief information about Reader class in Java:

The Reader class of the java.io package is an abstract superclass that represents a stream of characters. Since Reader is an abstract class, it is not useful by itself. However, its subclasses can be used to read data.




Different methods to achieve file reading in JAVA are listed below:


1.By using the BufferedReader class

2.By using the Scanner class

3.By using File Reader class

4.Reading files in a List

5.Read the file as a String

6.Reading a file using readString method


Description:


1) Using BufferedReader class


Reads text from character files using a default buffer size. Decoding from bytes to characters either uses a specified charset or the platform's default charset.


What does it mean technically???

Reads text from character files using a default buffer size: The statement implies, that the method or class being described is used to read text from files that contain characters (like letters, numbers, symbols). It does so by reading a certain amount of text at a time, known as a buffer. <This buffer size is predefined by the system and is used by default>


Decoding from bytes to characters uses either a specified charset or the platform's default charset. Process is listed below:



package fileread;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileReading_BufferedReaderClass {

public static void main(String[] args) {
String path="<Directory Path>\\Reading_file.txt";
File file=new File(path);
FileReader fil=null;
try {
fil = new FileReader(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int count=0;
BufferedReader br=new BufferedReader(fil);
try {
while((count=br.read())!=-1) {
System.out.print((char)count);

}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


2) Scanner class to read file- Reading a .txt file using Scanner class in Java???? How to do it & why it's required!

The Scanner class in Java is a versatile tool for reading input from various sources, including formatted text files. It's particularly useful for parsing different types of data from the input stream, making it easier to work with input data in your Java programs. Parsing means interpreting the raw input data and converting it into a specific data type that your program can work with.


nextLine() method flow representation:



package fileread;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileReadingUsingScannerClass {

public static void readFile(String filePath){

try {
File myObj=new File(filePath);
Scanner myReader=new Scanner(myObj);
while(myReader.hasNextLine()){
String data=myReader.nextLine();
System.out.println(data);
}
catch(FileNotFoundException e)
{
System.out.println("An error occured while reading..");
e.printStackTrace();
}
}
public static void main(String[] args) {
String filePath="<Directory Path>\\Reading_file.txt";
readFile(filePath) ;


}
}




3) Using Filereader class:


The java.io.FileReader class in Java is used to read text from character files with the following features:

  1. It uses a default buffer size for efficient reading.
  2. It decodes binary data into characters using either a specified charset or the platform's default charset.


package fileread;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileReading_FileReaderClass {
public static void main(String[] args) {
String filePath="<Directory Path>\\Reading_file.txt";
readFile(filePath) ;
}

public static void readFile(String path){
FileReader filRead=null;
try {
filRead=new FileReader(path);
System.out.println("File contains");
int count=0;
while((count=filRead.read() )!=-1) {
System.out.print((char)count);
}
}
catch(Exception e) {
e.printStackTrace();
}
finally {
try {
filRead.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}


4) Reading file as a List:

This method reads all lines from the file specified by the filePath. It returns a list of strings where each element represents a line from the file.

Here we should also know the difference between (Path and Paths) & (File and Files):

























package fileread;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class FileReadingUsingNIO {

public static void main(String[] args) {

Path filePath = Paths.get("<Directory Path>\\Reading_file.txt");

try {
// Read all lines from the file into a list
List<String> lines = Files.readAllLines(filePath);

// Print each line
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}


5) Read file as a String:

The method Files.readAllBytes() reads all the bytes from a file specified by the path, converts them into a string, and stores the result in the variable text.The method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown.

Note that this method is intended for simple cases where it is convenient to read all bytes into a byte array. It is not intended for reading in large files.The explanation of below code snippet is as follows:


package fileread;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ReadingFileAsString {

public static void main(String[] args) {
Path path = Paths.get("<Directory Path>\\Reading_file.txt");

String data = "";
try {
data = new String( Files.readAllBytes(path));
} catch (IOException e) {

e.printStackTrace();
}
System.out.println(data);
}
}



6) Using readString:


This method reads the entire contents of the file into a single String object. It provides simplicity when you need to read the entire file as a single String without processing line by line.


package fileread;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;

public class Test12 {

public static void main(String[] args) {
Path path =Paths.get("<Directory Path>\\Reading_file.txt");

String contents = null;
try {
contents = Files.readString(path, StandardCharsets.ISO_8859_1);
System.out.println(contents);
} catch (IOException ex) {
// Handle exception
}
}
}



Summary:

In a nutshell,

The code for the examples is available over on GitHub.


Github Repository


All Comments ()
Do You want to add Comment in this Blog? Please Login ?