Java Read File to String

Learn to read a text file into String in Java. Following examples use Files.readAllBytes(), Files.lines() (to read line by line) and FileReader and BufferedReader to read a file to String.

1. Files.readString() – Java 11

With the new method readString() introduced in Java 11, it takes only a single line to read a file’s content into String.

Example 1: Read a file to String in Java 11

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class WriteToFile
{
	public static void main(String[] args) throws IOException
	{
		Path fileName = Path.of("demo.txt");
	    String content  = "hello world !!";
	    Files.writeString(fileName, content);

	    String actual = Files.readString(fileName);
	    System.out.println(actual);
	}
}

2. Files.lines() – Java 8

The lines() method reads all lines from a file into a Stream. The Stream is populated lazily when the stream is consumed.

Bytes from the file are decoded into characters using the specified charset.

Example 2: Reading a file line by line in Java 8

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class ReadFileToString
{
	public static void main(String[] args)
	{
		String filePath = "c:/temp/data.txt";

		System.out.println( readLineByLineJava8( filePath ) );
	}

	//Read file content into the string with - Files.lines(Path path, Charset cs)

	private static String readLineByLineJava8(String filePath)
	{
		StringBuilder contentBuilder = new StringBuilder();

		try (Stream<String> stream = Files.lines( Paths.get(filePath), StandardCharsets.UTF_8))
		{
			stream.forEach(s -> contentBuilder.append(s).append("\n"));
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}

		return contentBuilder.toString();
	}
}

3. Files.readAllBytes() – Read the entire File into String – Java 7

The readAllBytes() method reads all the bytes from a file.

This method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown. After reading all the bytes, we pass those bytes to String class constructor to create a new String.

Example 3: Java program to read entire file to String

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
 
public class ReadFileToString 
{
    public static void main(String[] args) 
    {
        String filePath = "c:/temp/data.txt";
 
        System.out.println( readAllBytesJava7( filePath ) );
    }
 
    //Read file content into string with - Files.readAllBytes(Path path)
 
    private static String readAllBytesJava7(String filePath) 
    {
        String content = "";
 
        try
        {
            content = new String ( Files.readAllBytes( Paths.get(filePath) ) );
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
 
        return content;
    }
}

4. BufferedReader – Java 6 and Below

If you are still not using Java 7 or later, then use BufferedReader class. Its readLine() method reads the file one line at a time and returns the content.

Example 4: Java program to read a file line by line

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
 
public class ReadFileToString 
{
    public static void main(String[] args) 
    {
        String filePath = "c:/temp/data.txt";
 
        System.out.println( usingBufferedReader( filePath ) );
    }
 
    //Read file content into the string with - using BufferedReader and FileReader
    //You can use this if you are still not using Java 8
 
    private static String usingBufferedReader(String filePath) 
    {
        StringBuilder contentBuilder = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) 
        {
 
            String sCurrentLine;
            while ((sCurrentLine = br.readLine()) != null) 
            {
                contentBuilder.append(sCurrentLine).append("\n");
            }
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
        return contentBuilder.toString();
    }
}

Use any of the above-given methods for reading a file into a string using Java.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

1 thought on “Java Read File to String”

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.