Java java.nio.file.Files readAllLines()Method

Java File Java java.nio.file.Files

readAllLines()The method is used to read all line content from the file and return it asList<String>a List.

readAllLines()The method has two overloaded versions:

public static List<String> readAllLines(Path path) throws IOException

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

The first version reads the file using the default character set (UTF-8), and the second version allows you to specify a character set.

Parameter Description

Path path

  • Type:java.nio.file.Path
  • Description: The file path object to read
  • Example:
    Path filePath = Paths.get("example.txt");

Charset cs(Optional parameter)

  • Type:java.nio.charset.Charset
  • Description: The character set used to decode the file content
  • Common character sets:
    • StandardCharsets.UTF_8
    • StandardCharsets.ISO_8859_1
    • StandardCharsets.US_ASCII
  • Example:
    Charset charset = StandardCharsets.UTF_8;

Return Value

  • Type:List<String>
  • Description: A list containing all lines of the file, each element represents a line in the file
  • Note:
    • Line separator (e.g.,\nor\r\n) is not included in the returned string
    • If the file is empty, an empty list is returned
    • The order of the list matches the order of lines in the file

Exception Handling

readAllLines()The method may throw the following exceptions:

  1. IOException- If an I/O error occurs (e.g., the file does not exist)
  2. SecurityException- If there is insufficient permission to access the file

It is recommended to handle exceptions when using it:

Example

try {
    List<String> lines = Files.readAllLines(path);
    // process the read content
} catch (IOException e) {
    e.printStackTrace();
    // handle exceptions
}

Usage Examples

Example 1: Basic Usage

Example

import java.nio.file.*;
import java.util.List;

public class ReadFileExample {
    public static void main(String[] args) {
        Path filePath = Paths.get("example.txt");
       
        try {
            List<String> lines = Files.readAllLines(filePath);
           
            // print the file content
            for (String line : lines) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.err.println("Error reading file: " + e.getMessage());
        }
    }
}

Example 2: Specifying a Character Set

Example

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

public class ReadFileWithCharset {
    public static void main(String[] args) {
        Path filePath = Paths.get("example.txt");
       
        try {
            List<String> lines = Files.readAllLines(filePath, StandardCharsets.UTF_8);
           
            // process the file content
            lines.forEach(System.out::println);
        } catch (IOException e) {
            System.err.println("Error reading file: " + e.getMessage());
        }
    }
}

Notes

  1. File size: This method reads the entire file into memory at once, not suitable for processing very large files (e.g., files over several hundred MB)
  2. Character encoding: Make sure to use the correct character set, otherwise garbled text may occur
  3. : Different operating systems use different line endings (Windows uses, Unix/Linux uses\r\n), but\nwill handle these differences correctlyreadAllLines()Performance considerations
  4. : For large files, consider usingmethod for streaming processingBufferedReaderandlines()Alternatives

Alternatives

Example

Example

try (Stream<String> stream = Files.lines(path)) {
    stream.forEach(System.out::println);
} catch (IOException e) {
    e.printStackTrace();
}

Summary


Summary

Files.readAllLines()Other Extensions

Java File Java java.nio.file.Files

AI thinking...