How to Read in a File in Java with Examples

In this tutorial, we will learn how to read from a file in Java and also learn the different ways of reading a file in Java. This is recommended when dealing with multiple applications.

In addition, there are different ways in reading a text file in Java. For example, we can use FileReaderBufferedReader, or Scanner to read from file in Java.

In every service, it will offer something unique. For example, in the BufferedReader it will give the buffering of data for a quick reading while for the scanner it will give a parsing ability.

Here are the following methods used for reading a file in java:

  • BufferedReader class
  • Scanner class
  • File Reader class
  • Reading the whole file in a List
  • Read a text file as String

In Java programs, we can also read a text file either line by line using the BufferReader and Scanner. However, in Java SE 8 it will recommend another stream class java.util.stream.Stream. This is to provide a passive and more useful way to read a file.

Note: In practicing a good writing code such as flushing or closing streams, the Exception-Handling and etc., it has been ignored for a better understanding of a program by beginners as well.

Furthermore, we will discuss each of the methods to a higher extent and most importantly by planning to implement them through a compact java program. 

Used BufferedReader class Method

When using this method, a text is read from a character in input stream. It uses a buffer to read lines, arrays, and characters. A buffer size can be defined, or we can use the default size. The default is huge enough for better purposes.

Usually, every read request made of a reader will cause a comparable reading request to be made of the basic character or in byte stream. In addition, it is desirable to cover a BufferedReader around in any reader of which of the read() operations will be valuable.

For example, like the FileReaders and InputStreamReaders will be shown below.

BufferedReader in = new BufferedReader(Reader in, int size);
package com.javatpoint;  
import java.io.*;  
public class BufferedReaderExample {  
    public static void main(String args[])throws Exception{    
          FileReader fr=new FileReader("C:\\Users\\Windows\\Desktop\\java.txt");    
          BufferedReader br=new BufferedReader(fr);    
  
          int i;    
          while((i=br.read())!=-1){  
          System.out.print((char)i);  
          }  
          br.close();    
          fr.close();    
    }    
}   

Output:

BufferedReader class Method in java

Used FileReader class Method

This class is used for reading text files. The datatypes of this class will assume that a default character encoding and a default byte buffer size are applicable.

Here is the list of defined constructor:

  • FileReader(File file): This is to make a new FileReader, and to provide the File to read from.
  • FileReader(FileDescriptor fd): This is to make a new FileReader, and to provide the FileDescriptor to read from.
  • FileReader(String fileName): This is to make a new FileReader, and to provide the name of the file to read from.

Here is an example:

import java.io.*;
 
public class GFG {
 
    public static void main(String[] args) throws Exception
    {
 
        FileReader fr = new FileReader(
            "C:\\Users\\Windows\\Desktop\\java.txt");
 
        int i;
        while ((i = fr.read()) != -1)
 
            System.out.print((char)i);
    }
}

Output:

FileReader class Method Example

Used Scanner Class Method

An easy text scanner that uses regular expressions to determine primitive types and strings. The scanner will break its input through tokens by using a limited pattern, in a default match in whitespace. The output tokens it will convert into a value of various types in the next methods.

For example by using a for loop:

import java.io.File;
import java.util.Scanner;
public class ReadFromFileUsingScanner
{
public static void main(String[] args) throws Exception
{
	
	File file = new File("C:\\Users\\Windows\\Desktop\\java.txt");
	Scanner sc = new Scanner(file);

	while (sc.hasNextLine())
	System.out.println(sc.nextLine());
}
}

Output:

Scanner Class Method in Java

Here is the other example without using loops.


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\\Windows\\Desktop\\java.txt");
	Scanner sc = new Scanner(file);

	sc.useDelimiter("\\Z");

	System.out.println(sc.next());
}
}

Output:

 Scanner Class Method without using loops

Used Reading the whole file in a List Method

This is to read all the lines in a file. In this method which is to assure that the file is closed if all bytes have been read or an input/output error or other runtime exception will be thrown. They are used to decode the file’s bytes into characters which are used to define a charset.

Syntax used:

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

This method will create the following as a line terminators: 

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

Example of Reading the Whole 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)
	{

	e.printStackTrace();
	}
	return lines;
}
public static void main(String[] args)
{
	List l = readFileInList("C:\\Users\\Windows\\Desktop\\java.txt");

	Iterator<String> itr = l.iterator();
	while (itr.hasNext())
	System.out.println(itr.next());
}
}

Output:

Used Read a text file as String Method

This is the example of the read a text as string.


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\\Windows\\Desktop\\java.txt");
	System.out.println(data);
}
}

Output:

Used Read a text file as String Method

Conclusion

In conclusion, we already learn the Read in a File in Java with the help of examples and also learned the different methods used in reading a file in Java like BufferedReader class, Scanner class, File Reader class, Reading the whole file in a List and the Read a text file as String.

Leave a Comment