Java – Read File as String

To read the contents of a text file into a String in Java, the simplest choice on Java 11 and later is Files.readString(). On Java 8, a common approach is Files.readAllBytes() followed by conversion of the byte array to a string with an explicit character set.

You can also read a file through streams or process it line by line. The right method depends mainly on your Java version, the size of the file, whether line breaks must be preserved exactly, and the character encoding used by the file.

Read an entire file as String with Files.readString() in Java 11+

For Java 11 or later, Files.readString(Path) provides a direct way to read the complete contents of a file. The no-charset overload reads the text as UTF-8.

</>
Copy
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class ReadFileAsString {
    public static void main(String[] args) {
        Path path = Path.of("files/data.txt");

        try {
            String fileContents = Files.readString(path);
            System.out.print(fileContents);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

If files/data.txt contains two lines, the resulting string contains those line separators as part of the text.

Output

Hello reader! Welcome to www.tutorialkart.com.
Hi reader! Welcome to Java Tutorials.

Read a file as String with a specific character encoding

Character encoding matters when bytes are converted to Java characters. If you know the file’s encoding, specify it explicitly. The following example reads a UTF-8 file.

</>
Copy
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class ReadFileAsString {
    public static void main(String[] args) {
        Path path = Path.of("files/data.txt");

        try {
            String fileContents = Files.readString(path, StandardCharsets.UTF_8);
            System.out.print(fileContents);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Read File as String using BufferedInputStream

In this example, we will use BufferedInputStream as the main step to read the contents of a file to a string. Following is the sequence of steps.

  1. Create file object with the path of the text file.
  2. Create a FileInputStream with the file created in the above step.
  3. Using this FileInputStream, create a BufferedInputStream.
  4. Use BufferedInputStream.readAllBytes() to read all the bytes to a byte array.
  5. Create a String with the byte array passed as argument, so that it returns a String formed using the byte array.
  6. Close BufferedInputStream and FileInputStream to release any system resources associated with the streams.

ReadFileAsString.java

</>
Copy
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Java Example Program to Read File as Sting using BufferedInputStream
 */

public class ReadFileAsString {

	public static void main(String[] args) {
		File file = new File("files/data.txt");
		
		try (FileInputStream fis = new FileInputStream(file);
				BufferedInputStream bis = new BufferedInputStream(fis)) {
			//read all bytes from buffered input stream and create string out of it
			String fileContents = new String(bis.readAllBytes());
			System.out.print(fileContents);
			bis.close();
			fis.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

FileInputStream and BufferedInputStream can throw IOException, so this example uses try-with-resources. Try-with-resources closes the streams automatically when the block finishes. The explicit close() calls shown in the existing example are therefore redundant, but the example is kept unchanged.

Run the program from command prompt or in your favorite IDE.

Output

Hello reader! Welcome to www.tutorialkart.com.
Hi reader! Welcome to Java Tutorials.

readAllBytes() reads the complete stream into memory. Also note that the existing example constructs the string without specifying a charset, so it uses the platform default charset. When the file encoding is known, explicitly pass that charset when converting the bytes.

</>
Copy
String fileContents =
        new String(bis.readAllBytes(), StandardCharsets.UTF_8);

Read File as String using commons.io

In this example, we shall use apache’s commons.io package to read file as a string.

  1. Create file object with the path to the text file.
  2. Call the method FileUtils.readFileToString() and pass the file object as argument to it. The function returns data in file as String.

ReadFileAsString.java

</>
Copy
import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

/**
 * Java Example Program to Read File as Sting using commons.io
 */

public class ReadFileAsString {

	public static void main(String[] args) {
		File file = new File("files/data.txt");
		
		String fileContents = "";
		try {
			//read file as string
			fileContents = FileUtils.readFileToString(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		//print contents of file
		System.out.print(fileContents);
	}
}

Run the program and you get the following output.

Output

Hello reader! Welcome to www.tutorialkart.com.
Hi reader! Welcome to Java Tutorials.

If you use Apache Commons IO in new code, prefer an overload of FileUtils.readFileToString() that receives the file’s character set instead of relying on the platform default encoding.

</>
Copy
String fileContents =
        FileUtils.readFileToString(file, StandardCharsets.UTF_8);

Read a file as String in Java 8 with Files.readAllBytes()

Files.readString() is not available in Java 8. For Java 8 code, you can read all bytes from a Path and decode those bytes with a known charset.

</>
Copy
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ReadFileAsString {
    public static void main(String[] args) {
        try {
            byte[] bytes = Files.readAllBytes(Paths.get("files/data.txt"));
            String fileContents = new String(bytes, StandardCharsets.UTF_8);
            System.out.print(fileContents);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This approach is suitable when the complete file can reasonably be held in memory. It also works without an external library.

Convert a java.io.File to String with File.toPath()

If your code already has a java.io.File object, convert it to a Path with toPath() and pass that path to Files.readString() on Java 11 or later.

</>
Copy
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class FileToString {
    public static void main(String[] args) {
        File file = new File("files/data.txt");

        try {
            String fileContents = Files.readString(file.toPath());
            System.out.print(fileContents);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Read a JSON file as String in Java

A JSON file is a text file, so reading it as a string uses the same file APIs. The following example reads the complete JSON document into a Java String. Parsing that JSON into Java objects is a separate step and normally requires a JSON library.

</>
Copy
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class ReadJsonAsString {
    public static void main(String[] args) {
        try {
            String json = Files.readString(Path.of("files/data.json"));
            System.out.println(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Read a Java text file line by line instead of one large String

If the application needs to process a text file one line at a time, there is no need to first create one large string. Files.lines() returns a stream of lines, which can be processed as they are read. The stream should be closed after use.

</>
Copy
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class ReadFileLineByLine {
    public static void main(String[] args) {
        Path path = Paths.get("files/data.txt");

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

This line-by-line approach is often a better fit for large text files because your program does not need to materialize the whole file as one String before processing it.

What Java read() returns when reading file contents

The meaning of read() depends on whether you are using a byte stream or a character reader. InputStream.read() reads a byte and returns its value as an int, while Reader.read() reads a character and also returns an int. In both cases, a return value of -1 indicates the end of the stream. For reading an entire text file into one string, the higher-level methods shown above are usually clearer.

Choosing a Java file-to-String method by Java version and file size

MethodJava versionBest fit
Files.readString()Java 11+Simple whole-file text reads
Files.readAllBytes() + new String(...)Java 7+Whole-file reads when you need to decode bytes explicitly
Files.lines()Java 8+Processing text one line at a time
BufferedInputStreamJava I/O APICases where you are already working with byte streams
FileUtils.readFileToString()Apache Commons IO dependencyProjects that already use Commons IO

Java file path and IOException checks when reading text

All of these examples assume that files/data.txt exists relative to the program’s current working directory. A wrong relative path can result in a file-not-found error. Whole-file reading methods can also throw IOException, so the examples either catch that exception or can declare it with throws IOException.

When diagnosing a path problem, an absolute path can help confirm whether the issue is the current working directory. For portable application code, however, avoid hard-coding machine-specific paths when a configurable or application-relative location is more appropriate.

Java file-to-String method summary

For Java 11 and later, Files.readString() is the most direct standard-library method for reading an entire text file into a string. For Java 8, use Files.readAllBytes() with an explicit charset when the whole file fits comfortably in memory. If you need to process a large file incrementally, prefer a line-by-line or streaming approach instead of loading all content into one string.

In this Java Tutorial, we learned how to read File as String, using inbuilt classes and some external Java packages.