Read a Text File Line by Line in Java
· One min read
Reading a file line by line is appropriate for logs and other large text files because it avoids loading the complete file into memory. Always specify the character set and close streams reliably.
BufferedReader example
import com.google.gson.JsonObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class ConvertFile {
public static void main(String[] args) throws Exception {
Path input = Path.of("c:/error.txt");
Path output = Path.of("c:/errorJson.txt");
JsonObject json = new JsonObject();
try (BufferedReader reader = Files.newBufferedReader(
input, StandardCharsets.UTF_8)) {
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split("-", 2);
if (parts.length == 2) {
json.addProperty(parts[0], parts[1]);
}
}
}
try (BufferedWriter writer = Files.newBufferedWriter(
output, StandardCharsets.UTF_8)) {
writer.write(json.toString());
}
}
}
Using split("-", 2) prevents later hyphens in the value from creating extra array elements. Decide how malformed rows should be logged or rejected instead of silently assuming every line has the expected format.
Files.lines
try (var lines = Files.lines(input, StandardCharsets.UTF_8)) {
lines.forEach(System.out::println);
}
The returned Stream owns an open file handle and must be closed, so keep it inside try-with-resources.