File.stream-exclamation-mark
stream-exclamation-mark
, go back to File module for more information.
Specs
stream!(Path.t(), [stream_mode()], :line | pos_integer()) :: File.Stream.t()
Returns a File.Stream
for the given path
with the given modes
.
The stream implements both Enumerable
and Collectable
protocols,
which means it can be used both for read and write.
The line_or_bytes
argument configures how the file is read when
streaming, by :line
(default) or by a given number of bytes. When
using the :line
option, CRLF line breaks (" "
) are normalized
to LF (" "
).
Operating the stream can fail on open for the same reasons as
File.open!/2
. Note that the file is automatically opened each time streaming
begins. There is no need to pass :read
and :write
modes, as those are
automatically set by Elixir.
Raw files
Since Elixir controls when the streamed file is opened, the underlying
device cannot be shared and as such it is convenient to open the file
in raw mode for performance reasons. Therefore, Elixir will open
streams in :raw
mode with the :read_ahead
option unless an encoding
is specified. This means any data streamed into the file must be
converted to iodata/0
type. If you pass, for example, [encoding: :utf8]
or [encoding: {:utf16, :little}]
in the modes parameter,
the underlying stream will use IO.write/2
and the String.Chars
protocol
to convert the data. See IO.binwrite/2
and IO.write/2
.
One may also consider passing the :delayed_write
option if the stream
is meant to be written to under a tight loop.
Byte order marks
If you pass :trim_bom
in the modes parameter, the stream will
trim UTF-8, UTF-16 and UTF-32 byte order marks when reading from file.
Note that this function does not try to discover the file encoding basing on BOM.
Examples
# Read in 2048 byte chunks rather than lines
File.stream!("./test/test.data", [], 2048)
#=> %File.Stream{line_or_bytes: 2048, modes: [:raw, :read_ahead, :binary],
#=> path: "./test/test.data", raw: true}
See Stream.run/1
for an example of streaming into a file.