Streams over files
A file is a collection the program does not hold: it is on disk, it may be larger than memory, and the operating system hands it over in pieces. File.stream!/2 is the function of Elixir that turns a file into such a collection, one line at a time, so a pipeline over it uses the same functions as a pipeline over a list and never reads more than it needs.
File.stream!
The call answers a stream of lines, each line still ending with its newline. A trim in the pipeline is what makes the values the program wants, and the Enum call at the end is what reads the file. The program writes its own file first, so it runs on its own:
lines.exs
path = Path.join(System.tmp_dir!(), "stream_lines.txt") File.write!(path, "one\ntwo\nthree\n") lines = path |> File.stream!() |> Enum.map(&String.trim/1) IO.inspect(lines) File.rm!(path)
elixir lines.exs
["one", "two", "three"]
The file is opened when the stream is consumed and closed when the enumeration ends, so the program needs no File.close/1. The second argument of File.stream!/2 selects the mode: :line by default, or :bytes for fixed-size chunks. The bang in the name means a missing file raises rather than returning an error tuple.
Stop early
A stream reads only what the pipeline asks for, which is the difference from File.read!/1: the call below prints two lines of a three-line file and returns two items, because Stream.take/2 stops the enumeration:
stop.exs
path = Path.join(System.tmp_dir!(), "stream_stop.txt") File.write!(path, "a\nb\nc\n") first_two = path |> File.stream!() |> Stream.map(&String.trim/1) |> Stream.each(&IO.puts("line: #{&1}")) |> Stream.take(2) |> Enum.to_list() IO.inspect(first_two) File.rm!(path)
elixir stop.exs
line: a
line: b
["a", "b"]
The third line never reaches the print, and the file is closed when the enumeration stops early as well. This is the shape of a search: Stream.find/2 or a Stream.take_while/2 on a log of a million lines stops at the first answer and reads no further.
A file bigger than memory
The two ways to read a file differ in what they hold at once. File.read!/1 answers a binary of the whole file; a stream answers one line at a time, so the memory a program needs does not grow with the file:
count.exs
path = Path.join(System.tmp_dir!(), "stream_count.txt") File.write!(path, "a\nb\nc\nd\n") count = path |> File.stream!() |> Enum.count() IO.puts(count) File.rm!(path)
elixir count.exs
4
Counting four lines proves nothing about size, and the same three lines count a file of four million. Enum.count/1 on a stream keeps one number and one line at a time, where File.read!/1 would hold the whole text and String.split/2 would hold every line as well.
A row per line
A file of records is a stream of lines plus one function that turns a line into a value. The steps stay separate and each one is testable on its own: trim, drop the empty lines, split on the comma, convert the number:
parse.exs
path = Path.join(System.tmp_dir!(), "stream_rows.txt") File.write!(path, "ada,36\nbob,12\n") rows = path |> File.stream!() |> Stream.map(&String.trim/1) |> Stream.reject(&(&1 == "")) |> Stream.map(fn line -> [name, age] = String.split(line, ",") {name, String.to_integer(age)} end) |> Enum.to_list() IO.inspect(rows) File.rm!(path)
elixir parse.exs
[{"ada", 36}, {"bob", 12}]
A row that does not fit the pattern stops the program with a MatchError, which is the right answer for a file the program wrote itself and the wrong one for a file a user uploads. For the second case the parse function returns an :ok or an :error tuple and the pipeline counts the bad rows; the line-by-line lesson of the errors part builds exactly that.
The mistake: a file that is not there
File.stream!/2 takes a path that must exist, and the file is opened when the enumeration starts rather than at the call. A missing file therefore raises a File.Error at the first Enum step, with the path it tried:
mistake.exs
path = "missing.txt" IO.inspect(File.stream!(path) |> Enum.to_list())
elixir mistake.exs
** (File.Error) could not stream "missing.txt": no such file or directory
(elixir 1.19.7) lib/file/stream.ex:104: anonymous fn/3 in Enumerable.File.Stream.reduce/3
(elixir 1.19.7) lib/stream.ex:1561: anonymous fn/5 in Stream.resource/3
(elixir 1.19.7) lib/enum.ex:4570: Enum.reverse/1
(elixir 1.19.7) lib/enum.ex:3822: Enum.to_list/1
mistake.exs:3: (file)
The stack names the stream and the enumeration, not the line that built the path, which is why the path in the message matters. File.exists?/1 before the stream, or File.stream/2 without the bang with an explicit check, turns the crash into a decision the program makes. A path built from user input is checked before it is opened, never after.
The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
When is a file opened by
File.stream!/2?Answer
When the enumeration starts
The stream is a description; the file is opened when an Enum function asks for the first line.
-
What does the bang in
File.stream!/2mean?Answer
A missing file raises instead of returning an error tuple
The bang marks the version that raises; the other one returns an ok or error tuple.
-
Why does a stream of lines use less memory than
File.read!/1?Answer
Because it holds one line at a time rather than the whole text
The enumeration pulls one line, uses it, and asks for the next, so the file never has to fit.
-
What ends the reading of a file stream before its last line?
Answer
a Stream.take/2 or Stream.take_while/2 in the pipeline
A stream reads only what the final step asks for, so take stops the enumeration early.
-
What does this program print?
File.write!("t.txt", "a\nb\n") IO.inspect(File.stream!("t.txt") |> Enum.map(&String.trim/1) |> Enum.to_list())Answer
["a", "b"]
The stream yields one line at a time and the trim removes the newline of each.
-
What does this program print?
File.write!("t.txt", "a\nb\nc\n") IO.puts(File.stream!("t.txt") |> Enum.count())Answer
3
The file has three lines, and the count never builds the list.
-
What does each item of a line stream end with, before any trim?
Answer
a newline character
The line mode keeps the terminator, which is why String.trim/1 is the first step of most pipelines.
-
What does this program print?
File.write!("t.txt", "1\n2\n3\n") IO.inspect(File.stream!("t.txt") |> Stream.map(&String.trim/1) |> Stream.take(2) |> Enum.to_list())Answer
["1", "2"]
take asks for two lines and the file is read only that far.
-
What does this program do?
IO.inspect(File.stream!("missing.txt") |> Enum.to_list())Answer
A File.Error, because the file does not exist
The bang version raises at the first Enum step, naming the path it tried to open.
-
Which call reads a whole file into one binary?
Answer
File.read!/1
File.read!/1 returns the whole content as a binary; the stream reads it in pieces.
Автор статьи: Arthur Isaev