Java 8 Read File As Single String

Java 8 has added Files.lines() method, which can be used to read the file as Stream. Joining Collector Can be used to convert Stream to Single String.

Read file as a stream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class Java8ReadFileAsString {

public static void main(String[] args) throws IOException {
String filePath = "C:\\data\\demo\\sample.txt";
Stream<String> lines = Files.lines(Paths.get((filePath)));
String fileAsString = lines.collect(Collectors.joining());
System.out.println(fileAsString);
}

}
Sample.txt file for testing.
1
2
3
4
5
6
7
public final class Files extends Object
This class consists exclusively of static methods that operate on files, directories, or other types of files.
In most cases, the methods defined here will delegate to the associated file system provider to perform the file operations.

Since:
1.7

Share Comments