---
title: "How do you read a whole file into memory with Files.readAllBytes in Java?"
description: "Files.readAllBytes returns a file's contents as a byte array. See how to get a String, use Files.readString and avoid memory problems with large files."
url: "https://bugsee.com/answers/java/files-readallbytes/"
---

# How do you read a whole file into memory with Files.readAllBytes in Java?

`Files.readAllBytes(Path.of("file.txt"))` returns the file as a `byte[]`. Use `Files.readString(path)` on Java 11 or later when you want the text directly.

```java
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

Path path = Path.of("data", "notes.txt");

byte[] bytes = Files.readAllBytes(path);
String text = new String(bytes, StandardCharsets.UTF_8);

String text2 = Files.readString(path);            // Java 11+, UTF-8
List<String> lines = Files.readAllLines(path);    // one entry per line

// Large files: stream instead of loading everything
try (Stream<String> stream = Files.lines(path)) {
    stream.filter(line -> line.contains("ERROR")).forEach(System.out::println);
}
```

These methods throw `IOException`, so call them in a method that declares it or wrap them in try/catch. Reading a whole file needs memory about equal to its size, so use `Files.lines` or a buffered reader for large inputs.

## Related questions

- [How do you fix java.nio.file.NoSuchFileException?](https://bugsee.com/answers/java/java-nio-file-nosuchfileexception/)
- [How do you read a file from the classpath in Java?](https://bugsee.com/answers/java/java-read-file-from-classpath/)
