Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

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.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 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 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());
#include <fstream>
std::ifstream file (path);
for (std::string line; std::getline(file, line); lines.push_back(line)) {}
using System.IO;
using System.Collections.Generic;
using System.Linq;
        public List<string> GetLines(string _path)
        {
            return File.ReadAllLines(_path).ToList();
        }
import 'dart:io';
var lines = File(path).readAsLinesSync();
import "os"
import "strings"
func readLines(path string) ([]string, error) {
	b, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}
	lines := strings.Split(string(b), "\n")
	return lines, nil
}
import "os"
import "bytes"
func readLines(path string) ([][]byte, error) {
	b, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}
	lines := bytes.Split(b, []byte{'\n'})
	return lines, nil
}
import fs from "fs";
fs.readFileSync(path).split("\n")
import java.io.File
val lines = File(path).readLines()
$lines = file($path);
if ($lines === false)
  die("Can't open file $path");
uses Classes;
var
  Lines: TStringList;
...
  Lines := TStringList.Create;
  Lines.LoadFromFile(Path);
use Path::Tiny qw(path);
my @lines = path($path)->lines;
with open(path) as f:
    lines = f.readlines()
lines = open(path).readlines
use std::io::prelude::*;
use std::io::BufReader;
use std::fs::File;
let lines = BufReader::new(File::open(path).unwrap())
	.lines()
	.collect::<Vec<_>>();
Dim lines = IO.File.ReadAllLines(path).ToList

New implementation...
< >
Jadiker