Support Online
Skip to main content

Reading Files with Java: The Most Efficient Methods and Sample Codes

Java provides powerful tools for file reading operations.
In this guide, you will learn how to read files line by line, high performance and in different encodings with classes such as BufferedReader, Scanner, Files.readAllLines() and FileChannel.

🎯 What Will You Learn in This Guide?

  • Four different ways to read a file in Java
  • Manage different character encodings like UTF-8 and UTF-16
  • Processing large files in GB size efficiently
  • Differences between FileReader and BufferedReader
  • Error handling with try-with-resources

💻 1. Reading a File Line by Line with BufferedReader (Most Efficient Method)

BufferedReader is high-performance because it reads the file by buffering it.
The readLine() method returns null when the end of the file is reached.

📄 Sample Code:

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

public class ReadFileWithBufferedReader {
public static void main(String[] args) {
try (BufferedReader okuyucu = new BufferedReader(new FileReader("deneme.txt"))) {
String satir;
while ((satir = okuyucu.readLine()) != null) {
System.out.println(satir);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

💬 This code reads the trial.txt file line by line and prints it to the screen.


📘 2. Reading Files with Scanner

The Scanner class is ideal for simple file reading operations. The hasNextLine() method moves line by line until the end of the file.

📄 Sample Code:


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

public class ReadFileWithScanner {
public static void main(String[] args) {
try (Scanner tarayici = new Scanner(new File("deneme.txt"))) {
while (tarayici.hasNextLine()) {
System.out.println(tarayici.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

💬 Scanner offers a practical and readable solution for small files.


📄 3. Reading All Lines as a List with Files.readAllLines()

The Files.readAllLines() method encloses all lines in the file into an List<String>. Suitable for small files.

📄 Sample Code:


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

public class ReadFileWithFilesClass {
public static void main(String[] args) {
try {
List<String> satirlar = Files.readAllLines(Paths.get("deneme.txt"));
satirlar.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}

💬 You can easily process all file lines by listing them in a list.


📚 4. Reading with RandomAccessFile

RandomAccessFile can open the file in both read and write mode. The “r” parameter is used only for reading.

📄 Sample Code:


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

public class ReadFileWithRandomAccessFile {
public static void main(String[] args) {
try (RandomAccessFile dosya = new RandomAccessFile("deneme.txt", "r")) {
String str;
while ((str = dosya.readLine()) != null) {
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

💬 This method is ideal for starting reading from a specific part of the file.


🌐 Character Encoding Management

If your file is in an encoding other than UTF-8, you must specify the correct character set.

Reading with UTF-8


import java.nio.charset.StandardCharsets;
import java.nio.file.*;

public class ReadUTF8File {
public static void main(String[] args) {
try {
String icerik = Files.readString(Path.of("ornek.txt"), StandardCharsets.UTF_8);
System.out.println(icerik);
} catch (IOException e) {
e.printStackTrace();
}
}
}

💬 UTF-8 processes Turkish characters without any problems.

Reading with UTF-16


import java.nio.charset.Charset;
import java.nio.file.*;

public class ReadUTF16File {
public static void main(String[] args) {
try {
String icerik = Files.readString(Path.of("ornek.txt"), Charset.forName("UTF-16"));
System.out.println(icerik);
} catch (IOException e) {
e.printStackTrace();
}
}
}

💬 UTF-16 is widely used in Unicode supported systems.


⚡ Using NIO and FileChannel for Large Files

FileChannel provides high performance for GB-level log or data files. It processes file content piece by piece without overloading memory.

📄 Sample Code:


import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.*;

public class FileChannelExample {
public static void main(String[] args) {
try (FileChannel kanal = FileChannel.open(Path.of("buyukveri.log"), StandardOpenOption.READ)) {
ByteBuffer tampon = ByteBuffer.allocate(4096);
while (kanal.read(tampon) > 0) {
tampon.flip();
System.out.print(new String(tampon.array(), 0, tampon.limit()));
tampon.clear();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

💬 FileChannel improves performance by processing large files with small buffers.


❓ Frequently Asked Questions (FAQ)

  1. What is the most efficient method for reading files?

For large files, BufferedReader or FileChannel is recommended.

  1. What is the difference between FileReader and BufferedReader?

FileReader reads character by character, while BufferedReader works much faster by buffering.

  1. How to solve file not found error?

Make sure the file path is correct, check permissions and use the try-with-resources structure.

  1. Is it possible to read large files without loading them into memory?

Yes, the FileChannel or BufferedReader.lines() streaming methods can be used.

  1. What should be done if Turkish characters are corrupted?

If the file is not in UTF-8 encoding, select the appropriate character set such as Charset.forName("ISO-8859-9").


🔚 Result

In this guide, you learned the file reading methods in Java in detail. With different classes, character encodings and performance techniques, you can now easily read files of any size.

💡 Performance, error management and encoding selection are always critical in file operations. You can immediately try your Java applications on the GenixNode platform and create your cloud-based test environment. 🚀