HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / I/O / Java Read File to String

Java Read File to String

Learn to read file to string in Java. Given examples use Files.readAllBytes(), Files.lines() (to read line by line) and FileReader & BufferedReader to read text 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 in to 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

lines() method read all lines from a file to stream and populates lazily as 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();
	}
}

Output:

Welcome to howtodoinjava.com blog. 
Learn to grow.

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

readAllBytes() method reads all the bytes from a file. The 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 bytes, we pass those bytes to String class constructor to create a 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;
	}
}

Output:

Welcome to howtodoinjava.com blog. 
Learn to grow.

4. BufferedReader – Java 6 and below

If you are still not using Java 7 or later, then use BufferedReader class. It’s readLine() method reads the file one line at a time and return 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();
	}
}

Output:

Welcome to howtodoinjava.com blog. 
Learn to grow.

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

Happy Learning !!

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Luke

    April 21, 2020

    Thx thx thx(…) you saved my world 🙂

Comments are closed on this article!

Search Tutorials

Java IO

  • Java IO Introduction
  • Java How IO works?
  • Java IO vs NIO
  • Java Create File
  • Java Write to File
  • Java Append to File
  • Java Read File
  • Java Read File to String
  • Java Read File to Byte[]
  • Java Make File Read Only
  • Java Copy File
  • Java Copy Directory
  • Java Delete Directory
  • Java Current Working Directory
  • Java Read/Write Properties File
  • Java Read File from Resources
  • Java Read File from Classpath
  • Java Read/Write UTF-8 Data
  • Java Check if File Exist
  • Java Create Temporary File
  • Java Write to Temporary File
  • Java Delete Temporary File
  • Java Read from Console
  • Java Typesafe input using Scanner
  • Java Password Protected Zip
  • Java Unzip with Subdirectories
  • Java Generate SHA/MD5
  • Java Read CSV File
  • Java InputStream to String
  • Java String to InputStream
  • Java OutputStream to InputStream
  • Java InputStreamReader
  • Java BufferedReader
  • Java FileReader
  • Java LineNumberReader
  • Java StringReader
  • Java FileWriter
  • Java BufferedWriter
  • Java FilenameFilter
  • Java FileFilter

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)