Logo

Programming-Idioms

  • Pascal
  • Java

Idiom #197 Get a list of lines from a file

Retrieve the contents of file at path into a list of strings lines, in which each element is a line of the file.

import java.io.File;
import java.util.List;
import java.util.Scanner;
Scanner s = new Scanner(new File(path));
s.useDelimiter("\\R");
List<String> lines = s.tokens().toList();
s.close();
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.List;
FileReader R = new FileReader(path);
BufferedReader r = new BufferedReader(R);
List<String> lines = r.lines().toList();
r.close();
import static java.nio.file.Files.readAllLines;
import java.io.File;
import java.util.List;
File f = new File(path);
List<String> lines = readAllLines(f.toPath());
import java.io.File;
import java.nio.file.Files;
import java.util.List;
import java.util.stream.Collectors;
String text = Files.readString(new File(path).toPath());
List<String> lines = text.lines().collect(Collectors.toList());
import java.io.File;
import java.nio.file.Files;
import java.util.List;
List<String> lines = Files.readAllLines(new File(path).toPath());
uses Classes;
var
  Lines: TStringList;
...
  Lines := TStringList.Create;
  Lines.LoadFromFile(Path);

After the LoadFromFile the lines (in the StringList) are accessible (r/w) through its Strings[] property.
#include <fstream>
std::ifstream file (path);
for (std::string line; std::getline(file, line); lines.push_back(line)) {}

Push new line in lines happens only when std::getline() retrieved data.

file(path) opens file in read-only mode.
file will be closed by destructor

New implementation...
< >
Jadiker