Java read file to string - 5 simple ways

Educating everyone with the beauty of programming!!
Java read file to string - 5 simple ways

In this tutorial we will discuss 5 simple ways to read a file to string in Java. Writing real world application code in java involves file and string processing. Some of the common use cases to convert a file to string are as follows.

  1. Read a JSON file and parse content from it.
  2. Read a CSV file for machine learning input data.

There are numerous other use cases for this. So given the huge number of applications, in this how to guide, we will discuss 5 simple and handpicked ways to read or convert a file into a String in Java.

Depending upon your project configuration, you can use any of the following methods.

1. Using Java 1.11+ inbuilt Files package:
import java.nio.file.Files;
import java.nio.file.Path;

String result = Files.readString(Path.of("filePath"));

//To Write string to a file you can use 
String content = "Demo Content";
Files.writeString(filePath, content);

This method works with Java 1.11+

2. Using Java 1.8+ inbuilt Streams package:
String result = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);

This method works with Java 1.8+

3. Native Java Scanner way:
try (Scanner scanner = new Scanner(Paths.get(fileName), {
    String result = scanner.useDelimiter("\\A").next();   

Note that “\A” represents regex pattern for useDelimiter scanner method. “\A” stands for :start of a string! . So when this pattern is supplied, whole stream is ready into the scanner object.

4. Apache commons-io IOUtils way:
File file = new File("data.txt");
String result = FileUtils.readFileToString(file, StandardCharsets.UTF_8);

For this method, Apache commons-io library should be included into your project. You can include it with the below maven link:

5. Using Google Guava library:
String result = Files.toString(new File(path), Charsets.UTF_8);

For this method, Guava library should be included into your project. You can include it with the below maven link:

If you want to play around with actual InputStreams without any utility methods you can use the above style.

If you feel there are any other better ways to convert the streams or if you have any questions please comment below.

We hope you like this post. If you have any questions or suggestions or need any other additional info, please comment below.

We have started a coding community for most frequently used real world coding tips. You can join us here
TipSeason Facebook Group
TipSeason Discord channel
As a bonus, here is a simple tech tip to increase your productivity.

What do you want to learn next ? Drop a comment below!