5 Ways How To Read a Text File in Java

There are different ways to use Java to read a Text File. Let’s see some of the methods we can use Java to read the contents of a file. This article uses methods from the following Java classes java.io.BufferedReader, Files.readAllLines() , Scanner or with Java 8 Streams Files.lines().

Read Files using Files.readAllLines()

package net.lirent.java;

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

public class ReadFileLineByLineUsingBufferedReader {
	public static void main(String[] args) {
		BufferedReader reader;
		try {
			reader = new BufferedReader(new FileReader("input.txt"));
			String line = reader.readLine();

			while (line != null) {
				System.out.println(line);
				// read next line
				line = reader.readLine();
			}

			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

If you want to read a large file with the Files class, you can use the newBufferedReader() method to obtain an instance of BufferedReader class and read the file line by line using a BufferedReader.

Read Files using Files.readAllLines()

Here is the second example How to read a file using Files class.

package net.lirent.java;

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

public class ReadFileLineByLineUsingFiles {

	public static void main(String[] args) {
		try {
			List<String> allLines = Files.readAllLines(Paths.get("input.txt"));

			for (String line : allLines) {
				System.out.println(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

You can use also readAllBytes() to retrieve the data stored in the file to a byte array instead of a string array.

byte[] bytes = Files.readAllBytes(path);

Reading Files with Files.lines()

Java 8 introduced a new method to the Files class to read the whole file into a Stream of strings.

package net.lirent.java;

import java.io.IOException;
import java.nio.file.*;
import java.util.stream.Stream;

public class FileReaderWithFilesLines {
    public static void main(String[] args) throws IOException {
        String file = "input.txt";
        Path path = Paths.get(file);
        Stream<String> lines = Files.lines(path);

        lines.forEach(s -> System.out.println(s));
        lines.close();
    }
}

Reading Text Files in Java with Scanner

The default delimiter of the Scanner class is whitespace. But you can set the delimiter to another character or a regular expression. It also has various next methods, such as next(), nextInt(), nextLine(), and nextByte(), to convert content into different types.

package net.lirent.java;

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

public class FileReaderWithScanner {
    public static void main(String[] args) throws IOException{
        String file = "input.txt";
        Scanner scanner = new Scanner(new File(file));
        scanner.useDelimiter(" ");

        while(scanner.hasNext()){
            String next = scanner.next();
            System.out.println(next);
        }
        scanner.close();
    }
}

Reading a File Line-by-Line using RandomAccessFile

package net.lirent.java;

import java.io.IOException;
import java.io.RandomAccessFile;

public class ReadFileLineByLineUsingRandomAccessFile {

	public static void main(String[] args) {
		try {
			RandomAccessFile file = new RandomAccessFile("input.txt", "r");
			String str;

			while ((str = file.readLine()) != null) {
				System.out.println(str);
			}

			file.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

Lets us know in the comments below which is your favorite method for reading e File in Java!

Share your love

One comment

Leave a Reply

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