How to Read in a File in Java

This site contains affiliate links to products. We may receive a commission for purchases made through these links.

There are many ways to read and write files in Java. You perform this function every time you deal with an application. If you’re a Java beginner wondering, “how to read in a file in Java,” we’ve got you covered. There are several techniques you can try to read any text file.

This article explains the main methods and utilities so you can choose the one that best matches your needs. Each offers something special, like data buffering, parsing ability, etc. Read the descriptions of each method in detail to choose the one you need.

Note: All code examples from this article are taken from Geeks for Geeks and Bealdung.

What Is Java?

Java is a popular programming language used for web application coding. Developers have been using Java for more than 20 years now, and millions of applications rely on this language.

Java is an object-oriented, multi-platform, and network-centric language with its own platform. Overall, it’s a secure, fast, and reliable language for coding just about any software, from small mobile applications to large enterprise software.

Common Java Language Usages

As a versatile and free-of-charge programming language, Java creates distributed and localized software. Popular use cases include:

  • Game development – computer, mobile, and video games
  • Cloud computing – the possibility to run apps on a range of underlying platforms
  • Big data – data processing engines with large data sets and real-time data
  • Artificial intelligence – machine learning libraries, natural language processing, etc.
  • Internet of Things – for hardware and sensor programming

As you can see, Java has a wide use range. You may have difficulties running specific algorithms if you’re only learning this programming language or already have experience.

Not many beginner programmers know that you can read in any text file in Java. There are at least seven methods you can use to perform the task. But more on them below.

How to Read in a File in Java – Methods

The seven methods for reading files in Java we’ll cover include the following:

  • BufferedReader Class
  • File Reader Class
  • Scanner Class
  • Reading the file in a List
  • Reading the file as a String
  • Java NIO
  • StreamTokenizer

Note: You can use the Scanner and BufferedReader to read text files line by line. Starting from Java 8, there’s also a Stream class, “,” that offers a faster way to read files.

1. BufferedReader Class

The BufferedReader class allows you to read text files from character-input streams. The class buffers to make reading the arrays, characters, and lines more efficient. You can specify the size of the buffer or use the default size. In general, the default buffer size meets most needs.

The read requests with BufferedReader will make the corresponding read request have a byte stream or underlying character. So it’s best to wrap the BufferedReader around any Reader with costly read () operations. Examples include InputStreamReaders and FileReaders.

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

Code example of this includes:

“// Java Program to illustrate Reading from FileReader

// using BufferedReader Class

// Importing input output classes


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


// Note: Double backquote is to avoid compiler

// interpret words

// like \test as \t (i.e., as 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




2. FileReader Class

FileReader is a class in package that programmers use to read a set of characters from files. The FileReader class can use a specified charset or rely on the platform’s default charset used for byte-to-character decoding.

For those unfamiliar with the term, the charset is a class that defines methods for producing decoders and encoders and for recovering several names.

With the FileReader class, you can read character text files. The developers of this class assume the default byte-buffer size and character encoding are appropriate.

Below are the defined constructors for the FileReader class:

  • FileReader(File file) – Create a new FileReader after giving the file it can read from
  • FileReader (FileDescriptor fd) – Create a new FileReader after giving the FileDescriptor it can read from
  • FileReader(String fileName) – Create a new FileReader after giving it the file name it can read from
  • FileReader(String filename, Charset charset) – Create a new FileReader after giving it the File to read with the given charset

There are numerous methods for FileReader:

  • Read() – read and pass a single or -1 character after ending the stream.
  • Read(char[]CharBuffer, int offset, int length) – read a character stream and store it in the Character Buffer. Offest refers to the position where it starts to read, and Length is the number of characters that need to be read.
  • Ready() – Shows whether the stream can be read. The stream is ready if the input buffer isn’t empty or blank.
  • Close() – Close the stream and release the associated resources
  • getEncoding() – Return the character encoding title that the stream uses

Example includes:

“// Java Program to Illustrate reading from

// FileReader using FileReader class

// Importing input output classes


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


// Declaring loop variable

int i;

// Holds true till there is nothing to read

while ((i = != -1)

// Print all the content of a file




3. Scanner Class

The Scanner class in Java is part of the java.util package that first saw the light of day with Java 1.5. Developers mostly use this class for receiving user input and parsing it into primitive data types like int, default String, or double. The Scanner is a utility class that parses data using regular expressions and token generation.

There are many constructors in the Scanner class:

  • Scanner(Path)
  • Scanner(String)
  • Scanner(File)
  • Scanner(InputSteram)
  • Scanner(InputStream, Charset)
  • Scanner(File, String)
  • Scanner(ReadagbleByteChannel)
  • Scanner(ReadablyByteChannel, Charset)

Most constructors rely on one of the following objects:

  • File or Path – Allows data scanning and working from values in the scanned data
  • String – Creates a scanner for the string source and parsing its values
  • InputStream – Where the is passed for user input information

With Scanner, you can divide the input using delimiter patterns that match the whitespace. The input is broken into tokens you can then convert into different type values. You can do so by relying on various methods.

With Loops

Here is a code example of using the Loops method:

“// Java Program to illustrate

// reading from Text File

// using Scanner Class


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())




Without Loops


“// Java Program to illustrate reading from FileReader

// using Scanner Class reading entire File

// without using loop



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





How to Read in a File in Java

4. List

The Java list method is an ordered collection and an extension to the Collection interface. This method allows developers greater control over where they can insert elements. The elements in the List can be accessed by the index or by element search in the list.

Java list has the following essential points:

  • Its interface is part of the Java Collections Framework.
  • It lets you add duplicate elements.
  • It allows “null” elements.
  • It has numerous default methods in Java 8, like sort, replaceAll, and spliterator.
  • The index in List starts from 0, much like arrays.
  • It works with Generics and should be combined with it whenever possible.

Using the List method, you can also read all lines from a text file. With it, the file remains closed when the bytes get read, or there’s an I/O error, and any other runtime exception gets thrown. A specified charset decodes the bytes from the file into characters.

The syntax for reading the file through List is:

Public static List readAllLines(Path path, Charset cs)throws I0Exception

You can use the following line terminators:

  • \u000D following \u000A, CARRIAGE RETURN following LINE FEED
  • \u000A, LINE FEED

Here’s a code example:

“// Java program to illustrate reading data from file

// using nio.File

import java.util.*;

import java.nio.charset.StandardCharsets;

import java.nio.file.*;


public class ReadFileIntoList


public static List<String> readFileInList(String fileName)


List<String> lines = Collections.emptyList();



lines =

Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);


catch (IOException e)


// do something



return lines;


public static void main(String[] args)


List l = readFileInList(“C:\\Users\\pankaj\\Desktop\\”);

Iterator<String> itr = l.iterator();

while (itr.hasNext())




5. String

Another option is to read a text file in Java as a String.

“// 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\\FolderName\\Desktop\\File.Name”);




6. Java NIO

The NIO package received numerous updates in JDK7. Here’s an example of the Files class and readAllLines method that accepts a Path. You can think of the Path class as an upgrade to with updated operations.

Small File Reading

Here’s how you can use the Files class to read a small file:


public void whenReadSmallFileJava7_thenCorrect()

throws IOException {

String expected_value = “Hello, world!”;

Path path = Paths.get(“src/test/resources/fileTest.txt”);

String read = Files.readAllLines(path).get(0);

assertEquals(expected_value, read);


You can also use readAllBytes () if you need to read binary data.

Reading Large Files

If you need to read a large file, you can do so with the Files class with the help of BufferedReader. Here’s a code that reads files using the BufferedReader and the new Files class:


public void whenReadLargeFileJava7_thenCorrect()

throws IOException {

String expected_value = “Hello, world!”;

Path path = Paths.get(“src/test/resources/fileTest.txt”);

BufferedReader reader = Files.newBufferedReader(path);

String line = reader.readLine();

assertEquals(expected_value, line);


Reading a File With Files.lines()

In JDK8, you can use the lines() method in the Files class. As a return, you get Stream of String elements.

Here’s an example of how you can read data into bytes and decode everything with the help of UTF-8 charset:

The code below uses the Files.lines() to read files.


public void givenFilePath_whenUsingFilesLines_thenFileData() {

String expectedData = “Hello, world!”;

Path path = Paths.get(getClass().getClassLoader()


Stream<String> lines = Files.lines(path);

String data = lines.collect(Collectors.joining(“\n”));


Assert.assertEquals(expectedData, data.trim());


When you use Stream with IO channels (file operations, for example), you need to close the stream with the close() method.

And as you can see, you can use the Files API to read the content of a file in a String more efficiently.

7. StreamTokenizer

You can also read a text file in tokens. This is possible via StreamTokenizer.

The tokenizer figures out the next token and determines whether it’s a number or a String. You can do so by examining the tokenizer.ttype field.

After you’re done, you read the token based on the type:

  • Tokenizer.nval for numbers
  • Tokenizer.sval for Strings

To read an input file saying “Hello 2,” you’ll use the following code:


public void whenReadWithStreamTokenizer_thenCorrectTokens()

throws IOException {

String file = “src/test/resources/fileTestTokenizer.txt”;

FileReader reader = new FileReader(file);

StreamTokenizer tokenizer = new StreamTokenizer(reader);

// token 1


assertEquals(StreamTokenizer.TT_WORD, tokenizer.ttype);

assertEquals(“Hello”, tokenizer.sval);

// token 2


assertEquals(StreamTokenizer.TT_NUMBER, tokenizer.ttype);

assertEquals(2, tokenizer.nval, 0.0000002);

// token 3


assertEquals(StreamTokenizer.TT_EOF, tokenizer.ttype);



Important Notes

Many classes are available for reading and writing files in Java, like FileReader, Scanner, BufferedReader, and others. The types we haven’t mentioned in this article include FileInputStream, FileWriter, and File0utputStream.

The class you use depends on your version of Java. Also, the choice will depend on the purpose of the action, like the need to read characters or bytes. Finally, the class choice varies depending on the size of the lines or file.

Reading in a File in Java – Explained

Whether you’re working on a new application or just practicing your Java skills, it’s helpful to know that you can read any text file in Java. You can rely on various classes like BufferedReader, FileReader, or Scanner. Also, it’s possible to read files as Lists and Strings.

Hopefully, the article above has helped you get started. We know learning Java can be challenging at times, but the important part is to take it one step at a time and jump those hurdles with patience.

Leave a Comment

Your email address will not be published. Required fields are marked *

Special offer for our visitors

Get your Free Coding Handbook

We will never send you spam. By signing up for this you agree with our privacy policy and to receive regular updates via email in regards to industry news and promotions