EN
Java read text from file (simple way)
3 points
xxxxxxxxxx
1
import java.io.IOException;
2
import java.nio.charset.StandardCharsets;
3
import java.nio.file.Files;
4
import java.nio.file.Path;
5
import java.nio.file.Paths;
6
import java.util.List;
7
8
public class ReadTextExample {
9
10
public static void main(String[] args) throws IOException {
11
12
Path path = Paths.get("C:\\projects\\text_file.txt");
13
14
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
15
16
for (String line : lines) {
17
System.out.println(line);
18
}
19
}
20
}
Output:
xxxxxxxxxx
1
line 1
2
line 2
3
line 3
We can also read entire text file in just 1 line of code in java:
new String(Files.readAllBytes(path))
xxxxxxxxxx
1
import java.io.IOException;
2
import java.nio.file.Files;
3
import java.nio.file.Path;
4
import java.nio.file.Paths;
5
6
public class ReadTextExample {
7
8
public static void main(String[] args) throws IOException {
9
10
Path path = Paths.get("C:\\projects\\text_file.txt");
11
12
String entireTextFile = new String(Files.readAllBytes(path));
13
14
System.out.println(entireTextFile);
15
}
16
}
Output:
xxxxxxxxxx
1
line 1
2
line 2
3
line 3
xxxxxxxxxx
1
import java.io.*;
2
import java.nio.charset.StandardCharsets;
3
import java.nio.file.Path;
4
import java.nio.file.Paths;
5
6
public class FileUtils {
7
8
public static String readText(Path path) throws IOException {
9
File file = path.toFile();
10
11
StringBuilder builder = new StringBuilder();
12
char[] buffer = new char[1024];
13
14
try (InputStream stream = new FileInputStream(file);
15
Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)
16
) {
17
while (true) {
18
int count = reader.read(buffer, 0, buffer.length);
19
20
if (count == -1)
21
break;
22
23
builder.append(buffer, 0, count);
24
}
25
}
26
27
return builder.toString();
28
}
29
30
// usage example:
31
public static void main(String[] args) throws IOException {
32
33
String text = FileUtils.readText(Paths.get("C:\\projects\\text_file.txt"));
34
35
System.out.println(text);
36
}
37
}
Output:
xxxxxxxxxx
1
line 1
2
line 2
3
line 3
Input data preparation for examples in this article.

File path under Windows operating system:
xxxxxxxxxx
1
C:\\projects\\text_file.txt
File content:
xxxxxxxxxx
1
line 1
2
line 2
3
line 3