您需要使用File.stream!
打開流模式文件,並Stream.into
和Stream.run
將數據寫入到文件:
iex(1)> file = File.stream!("a.txt")
%File.Stream{line_or_bytes: :line, modes: [:raw, :read_ahead, :binary],
path: "a.txt", raw: true}
iex(2)> ["hello", "my", "friend"] |> Stream.map(&String.replace(&1, ~r{[aeiou]}, "_")) |> Stream.into(file) |> Stream.run
:ok
iex(3)> File.read!("a.txt")
"h_ll_myfr__nd"
編輯:正如@FredtheMagicWonderDog所指出的那樣,最好只做|> Enum.into(file)
而不是|> Stream.into(file) |> Stream.run
。
iex(1)> file = File.stream!("a.txt")
%File.Stream{line_or_bytes: :line, modes: [:raw, :read_ahead, :binary],
path: "a.txt", raw: true}
iex(2)> ["hello", "my", "friend"] |> Stream.map(&String.replace(&1, ~r{[aeiou]}, "_")) |> Enum.into(file)
%File.Stream{line_or_bytes: :line, modes: [:raw, :read_ahead, :binary],
path: "a.txt", raw: true}
iex(3)> File.read!("a.txt")
"h_ll_myfr__nd"
我想你可以只用'Enum.into'以及而非'Stream.into |> Stream.run' –
如果該文件不存在發生? 如果文件不存在,您可以在寫入時創建嗎? – Asincrono
你是否仍然想使用'Stream.into |> Stream.run'?由於'Enum'函數是渴望的,'Stream'函數是懶惰的。 –