Two ways to read a File in a String with Java

Do you need to read a File into a String in Java ? This article will show two simple ways to achieve it. By the end of it, you will also learn the differences between each solution.

Solution #1 Use Files.readAllBytes

The first solution, which reads a file into an array of Bytes, uses the method Files.readAllBytes from a Path:

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

public class Main {
   public static void main(String[] args) throws IOException { 
      String text = new String(Files.readAllBytes(Paths.get("myfile.txt")));
      System.out.println(text); 
   } 
}

Solution #2 Use Files.readString

The second solution, uses the method readString of the Files Class to read a File into a String

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

public class Main {
   public static void main(String[] args) throws IOException { 
      String text =  Files.readString(Path.of("myfile.txt"));
      System.out.println(text); 
   } 
}

Comparing the two approaches

Both Files.readString and new String(Files.readAllBytes(Paths.get("myfile.txt"))) can be used to read a file into a string in Java. However, there are some differences between the two approaches.

  1. Return Type:
    • Files.readString returns the file content as a String.
    • Files.readAllBytes returns the file content as a byte[], which is then converted to a String using the String constructor.
  2. Charset Encoding:
    • Files.readString automatically detects the encoding of the file based on its content. It uses the default charset if the file encoding cannot be determined.
    • Files.readAllBytes reads the file content as a byte array without any charset encoding. It reads the raw bytes from the file.
  3. Convenience:
    • Files.readString is a more convenient method as it directly returns the file content as a String, eliminating the need for an additional conversion step.
    • Files.readAllBytes requires an extra step of converting the byte array to a String using the String constructor.

In terms of simplicity and conciseness, Files.readString is generally considered more straightforward as it directly returns the file content as a String without the need for additional conversions. However, if you require fine-grained control over the charset encoding or if you prefer working with raw bytes before converting them to a String, then Files.readAllBytes may be a better choice.

Found the article helpful? if so please follow us on Socials