Read a File to a String in Java

  1. Files.readString() to Read a String From File in Java 11
  2. Files.lines(file_path) to Read File to String in Java 8
  3. Files.readAllLines() to Read String From File in Java 7
  4. BufferedReader.readLine to Read String From a File

We will introduce how we can read the content of a file and then convert it into a Java string.

Below is the testFile.txt file, which includes some content we want to read as a Java string.

A
B
C
D
1
2
3

Files.readString() to Read a String From File in Java 11

Java 11 brings a new method Files.readString() which allows us to read the file easily and without writing lots of code.


import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {

    public static void main(String[] args) {

        Path path = Paths.get("/Projects/testFile.txt");
      
        try {
            String content = Files.readString(path);
            System.out.println(content);
        }catch (IOException e){
            e.printStackTrace();
        }

        }
}

Output:

A
B
C
D
1
2
3

Files.lines(file_path) to Read File to String in Java 8

The Stream API was introduced in Java 8 which processes the given set of data in various ways.

The class Files, as a part of the java.NIO package, contains a lines() method that produces Stream<String> or a stream of string from a text file.

Let’s try to convert the file contents into Java string using Stream API.


import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {

    public static void main(String[] args){

      try{
        Path path = Paths.get("/Projects/testFile.txt");
        Stream<String> lines = Files.lines(path);

            String content = lines.collect(Collectors.joining(System.lineSeparator()));
            System.out.println(content);
            lines.close();
      }catch(IOException e){
        e.printStackTrace();
      }
    }
}

Output:

A
B
C
D
1
2
3
Note

Always keep in mind to close the stream after using it. Notice the lines.close().

It ensures that the stream is closed once the content has been printed.

Files.readAllLines() to Read String From File in Java 7

Reading files was not that easy until Java 7, which brought the new method to the java.nio package. It is the Files.readAllLines() method which returns a list of strings from the file. Each string represents a single line of the file.

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class Main {

    public static void main(String[] args) {

        try {

            Path path = Paths.get("/Projects/testFile.txt");
            List<String> contentList = Files.readAllLines(path, StandardCharsets.UTF_8);
            System.out.println(contentList);
            
        }catch (IOException e){
            e.printStackTrace();
        } 
    } 
} 

Output:

[A, B, C, D, 1, 2, 3]

BufferedReader.readLine to Read String From a File

We can also get our file’s contents using the BufferedReader class, which reads the text from an input stream.


import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {

    public static void main(String[] args) throws IOException {

        String path = "/Projects/testFile.txt";

        try (BufferedReader br = new BufferedReader(new FileReader(path))) {

            String line = br.readLine();
            StringBuilder sb = new StringBuilder();

            while (line != null) {
                sb.append(line).append("\n");
                line = br.readLine();
            }

            String fileAsString = sb.toString();
            System.out.println(fileAsString);
        }
}
}

Output:

A
B
C
D
1
2
3
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Java String

  • Convert Float to String and String to Float in Java
  • Convert a String to Char in Java
  • Related Article - Java File

  • Save a String to a File in Java
  • Convert an Array to String in Java