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

title = “How to read a file to a string in Java” date = 2020-09-16T12:06:24+02:00 draft = false keywords = [“convert file to string”, “java-io”, “read string from file”] description = “Take a look at the several methods by which we can read and convert the file content into a Java string” inarticle = true tags = [“Java”, “Java String”, “Java File”] author = “Rupam Yadav” postlink = 326390

+++

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
comments powered by Disqus