Read all text from a file

Java 11 added the readString() method to read small files as a String, preserving line terminators:

CopyString content = Files.readString(path, encoding);

For versions between Java 7 and 11, here's a compact, robust idiom, wrapped up in a utility method:

Copystatic String readFile(String path, Charset encoding)
  throws IOException
{
  byte[] encoded = Files.readAllBytes(Paths.get(path));
  return new String(encoded, encoding);
}

Read lines of text from a file

Java 7 added a convenience method to read a file as lines of text, represented as a List<String>. This approach is "lossy" because the line separators are stripped from the end of each line.

CopyList<String> lines = Files.readAllLines(Paths.get(path), encoding);

Java 8 added the Files.lines() method to produce a Stream<String>. Again, this method is lossy because line separators are stripped. If an IOException is encountered while reading the file, it is wrapped in an UncheckedIOException, since Stream doesn't accept lambdas that throw checked exceptions.

Copytry (Stream<String> lines = Files.lines(path, encoding)) {
  lines.forEach(System.out::println);
}

This Stream does need a close() call; this is poorly documented on the API, and I suspect many people don't even notice Stream has a close() method. Be sure to use an ARM-block as shown.

If you are working with a source other than a file, you can use the lines() method in BufferedReader instead.

Memory utilization

If your file is small enough relative to your available memory, reading the entire file at once might work fine. However, if your file is too large, reading one line at a time, processing it, and then discarding it before moving on to the next could be a better approach. Stream processing in this way can eliminate the total file size as a factor in your memory requirement.

Character encoding

One thing that is missing from the sample in the original post is the character encoding. This encoding generally can't be determined from the file itself, and requires meta-data such as an HTTP header to convey this important information.

The StandardCharsets class defines some constants for the encodings required of all Java runtimes:

CopyString content = readFile("test.txt", StandardCharsets.UTF_8);

The platform default is available from the Charset class itself:

CopyString content = readFile("test.txt", Charset.defaultCharset());

There are some special cases where the platform default is what you want, but they are rare. You should be able justify your choice, because the platform default is not portable. One example where it might be correct is when reading standard input or writing standard output.


Note: This answer largely replaces my Java 6 version. The utility of Java 7 safely simplifies the code, and the old answer, which used a mapped byte buffer, prevented the file that was read from being deleted until the mapped buffer was garbage collected. You can view the old version via the "edited" link on this answer.

Answer from erickson on Stack Overflow
Top answer
1 of 16
1882

Read all text from a file

Java 11 added the readString() method to read small files as a String, preserving line terminators:

CopyString content = Files.readString(path, encoding);

For versions between Java 7 and 11, here's a compact, robust idiom, wrapped up in a utility method:

Copystatic String readFile(String path, Charset encoding)
  throws IOException
{
  byte[] encoded = Files.readAllBytes(Paths.get(path));
  return new String(encoded, encoding);
}

Read lines of text from a file

Java 7 added a convenience method to read a file as lines of text, represented as a List<String>. This approach is "lossy" because the line separators are stripped from the end of each line.

CopyList<String> lines = Files.readAllLines(Paths.get(path), encoding);

Java 8 added the Files.lines() method to produce a Stream<String>. Again, this method is lossy because line separators are stripped. If an IOException is encountered while reading the file, it is wrapped in an UncheckedIOException, since Stream doesn't accept lambdas that throw checked exceptions.

Copytry (Stream<String> lines = Files.lines(path, encoding)) {
  lines.forEach(System.out::println);
}

This Stream does need a close() call; this is poorly documented on the API, and I suspect many people don't even notice Stream has a close() method. Be sure to use an ARM-block as shown.

If you are working with a source other than a file, you can use the lines() method in BufferedReader instead.

Memory utilization

If your file is small enough relative to your available memory, reading the entire file at once might work fine. However, if your file is too large, reading one line at a time, processing it, and then discarding it before moving on to the next could be a better approach. Stream processing in this way can eliminate the total file size as a factor in your memory requirement.

Character encoding

One thing that is missing from the sample in the original post is the character encoding. This encoding generally can't be determined from the file itself, and requires meta-data such as an HTTP header to convey this important information.

The StandardCharsets class defines some constants for the encodings required of all Java runtimes:

CopyString content = readFile("test.txt", StandardCharsets.UTF_8);

The platform default is available from the Charset class itself:

CopyString content = readFile("test.txt", Charset.defaultCharset());

There are some special cases where the platform default is what you want, but they are rare. You should be able justify your choice, because the platform default is not portable. One example where it might be correct is when reading standard input or writing standard output.


Note: This answer largely replaces my Java 6 version. The utility of Java 7 safely simplifies the code, and the old answer, which used a mapped byte buffer, prevented the file that was read from being deleted until the mapped buffer was garbage collected. You can view the old version via the "edited" link on this answer.

2 of 16
407

If you're willing to use an external library, check out Apache Commons IO (200KB JAR). It contains an org.apache.commons.io.FileUtils.readFileToString() method that allows you to read an entire File into a String with one line of code.

Example:

Copyimport java.io.*;
import java.nio.charset.*;
import org.apache.commons.io.*;

public String readFile() throws IOException {
    File file = new File("data.txt");
    return FileUtils.readFileToString(file, StandardCharsets.UTF_8);
}
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-read-a-file-to-string
Java Program to Read a File to String - GeeksforGeeks
July 23, 2025 - The readString() method of File Class in Java is used to read contents to the specified file. ... Return Value: This method returns the content of the file in String format.
Discussions

What is the most "modern" way to read a plain text file in Java?
Files.readString(Path) This reads all of the contents into a String. Or you can read into lines in a List with Files.readAllLines(Path) or to a Stream with Files.lines(path) More on reddit.com
🌐 r/learnjava
7
16
April 1, 2022
Reading in text file contents(tokens) using while loop. Stringbuffer questions.
I don't understand what you're trying to do so it's hard to suggest anything. And to be honest this seems like a classic example of an XY Problem. Do you have to use a Scanner? There are other ways to read file contents which may be more efficient depending on what you want to do. Is there a reason you're using a StringBuffer rather than, say, a StringBuilder? So you have the tokens appended to your StringBuffer but what do you intend to do with this? Most importantly: What are you trying to do with the file? What is the purpose of reading it? What do you intend to do with the file contents? More on reddit.com
🌐 r/learnjava
3
6
May 18, 2021
[2022 Day 2] Reading a text file into Java
Files.readAllLines() is handy. More on reddit.com
🌐 r/adventofcode
8
6
December 2, 2022
What is easiest way to read and write a text file ?
This link might help you http://www.beginwithjava.com/java/file-input-output/index.html More on reddit.com
🌐 r/learnjava
7
7
August 22, 2015
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-read-file-to-string
Java read file to String | DigitalOcean
August 3, 2022 - The scanner class is a quick way to read a text file to string in java.
🌐
Baeldung
baeldung.com › home › java › java io › how to read a file in java
How to Read a File in Java | Baeldung
January 8, 2024 - For a few examples, we’ll use ... the file and its contents explicitly. We’ll use a set of test examples with core Java classes only, and in the tests, we’ll use assertions with Hamcrest matchers. Tests will share a common readFromInputStream method that transforms an InputStream to String for easier ...
🌐
Medium
medium.com › @alxkm › how-to-read-a-file-into-a-string-in-java-multiple-approaches-6c781a1c3cbd
Java Interview: How to Read a File into a String in Java-Multiple Approaches | by Alex Klimenko | Medium
August 9, 2025 - This is the cleanest and most modern way to read a file into a String. import java.nio.file.Files; import java.nio.file.Path; String content = Files.readString(Path.of("path/to/file.txt"));
🌐
Swarthmore College
cs.swarthmore.edu › ~newhall › unixhelp › Java_files.html
Reading from text files in Java
Instead, we called next to read in the next valid String token "CSstudents" which skips over all leading white space (i.e. '\n') and returns the String "CSstudents". Also, note that this same code sequence would work if the input file was in this crazy format:
Find elsewhere
🌐
W3Schools
w3schools.com › java › java_files_read.asp
Java Read Files
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Practice Problems Java Server Java Syllabus Java Study Plan Java Interview Q&A ... In the previous chapters, you learned how to create and write to a file. In the following example, we use the Scanner class to read the contents of the text file we created in the previous chapter:
🌐
How to do in Java
howtodoinjava.com › home › i/o › java read file to string (with examples)
Java Read File to String (with Examples)
October 22, 2023 - After reading all the bytes, we pass those bytes to String class constructor to create a new String. Path filePath = Path.of("c:/temp/demo.txt"); String fileContent = ""; try { byte[] bytes = Files.readAllBytes(Paths.get(filePath)); fileContent = new String (bytes); } catch (IOException e) { //handle exception } If you are still not using Java 7 or later, then use BufferedReader class.
🌐
CodeSignal
codesignal.com › learn › courses › fundamentals-of-text-data-manipulation-in-java-1 › lessons › fundamentals-of-text-data-manipulation-in-java-reading-text-files
Reading Text Files in Java
Utilize Java's Files and Paths classes to open a file and manage the data through the readString method. Read the entire contents of a file from disk into a string variable.
🌐
Guvi
ftp.guvi.in › hub › java-examples-tutorial › read-file-to-string
How to Read a File to String in Java
In the example below, we are using FileReader class to read data from the file. An object of FileReader class points to the beginning of a file and we will print everything while it returns -1 because it indicates the end of the file and the data is appended to a String variable. import java.io.*; public class StudyTonight { public static void main(String[] args) throws Exception { FileReader fr = new FileReader("E:\\Studytonight\\sampledata.txt"); String fileData = ""; int c; while((c=fr.read()) != -1) fileData += (char)c; System.out.println(fileData); } }
🌐
Quora
quora.com › How-do-you-read-a-file-write-a-file-and-output-a-file-from-a-text-file-in-Java
How to read a file, write a file and output a file from a text file in Java - Quora
Answer: You can try something like this:- Note :- Commons IO jar is required for the following program to run ! [code]package FileIO; import http://org.apache.commons.io.FileUtils; import java.io.*; import http://java.net.MalformedURLException; import http://java.net.URISyntaxException; import...
🌐
MangoHost
mangohost.net › mangohost blog › java read file to string – efficient file reading
Java Read File to String – Efficient File Reading
August 3, 2025 - Java 11 introduced Files.readString(), which is now the simplest and most efficient way to read small to medium-sized files: import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.io.IOException; public class ModernFileReading { public static String readFileToString(String filePath) throws IOException { Path path = Paths.get(filePath); return Files.readString(path); } // With specific encoding public static String readFileWithEncoding(String filePath) throws IOException { Path path = Paths.get(filePath); return Files.readString(path, StandardCharsets.UTF_8); } // Alternative using readAllLines for processing public static String readFileUsingLines(String filePath) throws IOException { Path path = Paths.get(filePath); return String.join("\n", Files.readAllLines(path)); } }
🌐
Medium
medium.com › @AlexanderObregon › javas-files-readstring-method-explained-219f66db08ca
Java’s Files.readString() Method Explained | Medium
February 7, 2025 - Using BufferedReader with FileReader One of the most common methods to read text files in Java before Java 11 was using BufferedReader in combination with FileReader. This method reads text efficiently by buffering characters, reducing the number of read operations needed from the disk. ... import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class BufferedReaderExample { public static void main(String[] args) { String filePath = "example.txt"; StringBuilder content = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { String line; while ((line = reader.readLine()) != null) { content.append(line).append(System.lineSeparator()); } } catch (IOException e) { e.printStackTrace(); } System.out.println(content.toString()); } }
🌐
Stack Abuse
stackabuse.com › java-read-a-file-into-a-string
Java: Read a File Into a String
September 13, 2023 - Here's a list of all the classes and methods we'll go over: ... The Files class contains static methods for working with files and directories. A useful method is lines() which returns a stream of strings: Stream<String>. From this stream, one can obtain lines contained in a file. The method ...
🌐
Java67
java67.com › 2016 › 08 › how-to-read-text-file-as-string-in-java.html
How to read a text file as String in Java? Example | Java67
You iterate through the file, reading one line at a time using readLine() method and appending them into a StringBuilder until you reach the end of the file. You can still use this method if you are running on Java SE 6 or the lower version.
🌐
GitHub
gist.github.com › gkhays › 93a5ee9577c690bc5196
Some methods to read a file from disk into a string. · GitHub
Using IOUtils.toString ( Apache Utils ) String result = IOUtils. ... Using CharStreams ( guava ) String result = CharStreams. ... Using Scanner (JDK) ... Using Stream Api ( Java 8 ). ... Using parallel Stream Api ( Java 8 ). More items... See Read/convert an InputStream to a String.
🌐
Blogger
javarevisited.blogspot.com › 2015 › 09 › how-to-read-file-into-string-in-java-7.html
How to read File into String in Java 7, 8 with Example
July 27, 2022 - Many times you want to read contents of a file into String, but, unfortunately, it was not a trivial job in Java, at least not until JDK 1.7. In Java 8, you can read a file into String in just one line of code. Prior to the release of new File IO API, you have to write a lot of boilerplate code e.g.
🌐
Xing's Blog
xinghua24.github.io › Java › Java-Read-Files
Reading a File in Java | Xing's Blog
April 18, 2021 - We can get the classloader of a class and then use getResourceAsStream method to get resource as InputStream. After we get InputStream, we can use InputStream.readAllBytes method to convert InputStream to bytes and create String from the bytes. Example to read file in src/main/resources/com/xinghua24/file.txt assuming the class is in com.xinghua24 package.
🌐
Sentry
sentry.io › sentry answers › java › how to read a file in java
How to Read a File in Java | Sentry
The Files utility class has a very useful readAllLines() method that will read all the lines of a file. The method signature denotes that the lines will be read into a simple List of String ...