Java Files readAllLines() Method Example

Introduction

The Files.readAllLines() method in Java is part of the java.nio.file package and is used to read all lines from a file into a List<String>. This method is convenient for reading small files where the entire content can be loaded into memory without causing performance issues. It provides an easy way to read the content of a text file line by line.

Table of Contents

  1. Importing Required Packages
  2. Reading All Lines from a File with Files.readAllLines()
  3. Handling Exceptions
  4. Complete Example
  5. Conclusion

Importing Required Packages

To use the Files.readAllLines() method, you need to import the necessary classes from the java.nio.file package.

Example

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

Reading All Lines from a File with Files.readAllLines()

To read all lines from a file, you need to specify the path of the file. The Files.readAllLines() method takes a Path object as an argument and returns a List<String> containing all the lines of the file.

Example

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

public class ReadAllLinesExample {
    public static void main(String[] args) {
        Path filePath = Paths.get("example.txt");
        try {
            List<String> lines = Files.readAllLines(filePath);
            for (String line : lines) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In the example above, the Files.readAllLines() method reads all lines from a file named example.txt and prints each line to the console.

Handling Exceptions

When reading a file, several exceptions might be thrown:

  • IOException: If an I/O error occurs reading from the file or a malformed or unmappable byte sequence is read.
  • SecurityException: If a security manager exists and denies read access to the file.

Example with Exception Handling

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

public class ReadAllLinesWithExceptionHandlingExample {
    public static void main(String[] args) {
        Path filePath = Paths.get("example.txt");
        try {
            List<String> lines = Files.readAllLines(filePath);
            for (String line : lines) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.err.println("I/O error: " + e.getMessage());
        } catch (SecurityException e) {
            System.err.println("Access denied: " + e.getMessage());
        }
    }
}

In the example above, different exceptions are caught and handled appropriately, providing informative messages.

Complete Example

Here is a complete example demonstrating the reading of all lines from a file using the Files.readAllLines() method with proper exception handling.

ReadAllLinesExample.java

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

public class ReadAllLinesExample {
    public static void main(String[] args) {
        Path filePath = Paths.get("example.txt");
        try {
            List<String> lines = Files.readAllLines(filePath);
            System.out.println("File content:");
            for (String line : lines) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.err.println("I/O error: " + e.getMessage());
        } catch (SecurityException e) {
            System.err.println("Access denied: " + e.getMessage());
        }
    }
}

In this example, all lines from a file named example.txt are read and printed to the console. The code handles exceptions to ensure that informative messages are displayed if an error occurs.

Conclusion

The Files.readAllLines() method in Java provides a simple and efficient way to read all lines from a file into a List<String>. By understanding how to use this method and handle potential exceptions, you can effectively manage file reading operations in your Java applications. Remember to always handle exceptions appropriately to ensure your application can respond to errors gracefully.

Comments