EN
Java - create string from file content
0
points
In this article, we would like to show you how to create string from the content of a file in Java.
Example data
In the below examples, we will use the example.txt file with the following content.
example.txt:
line 1
line 2
line 3
1. Create string from file content using Files.readString
(Java 11)
In this example, we use Files.readString()
method to read from the file and save the result into the content
string.
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Example {
public static void main(String[] args) throws IOException {
Path path = Paths.get("C:\\directory\\example.txt");
String content = Files.readString(path, StandardCharsets.UTF_8);
System.out.println(content);
}
}
Output:
line 1
line 2
line 3
2. Create list of strings from file content using Files.readAllLines
In this example, we use Files.readAllLines
to create a list of strings from example.txt file content. Each line will be separated item inside the lines
list.
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class Example {
public static void main(String[] args) throws IOException {
Path path = Paths.get("C:\\directory\\example.txt");
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
System.out.println(lines);
}
}
Output:
[line 1, line 2, line 3]