如何在Elixir中流式传输文件?

Tho*_*wne 6 elixir

如何获取流并将每行写入文件?

假设我有一个单词文件,我使用File.stream进行流式传输!我对它们进行了一些转换(这里我用下划线替换元音),但后来我想把它写成一个新文件.我怎么做?我到目前为止最好的是:

iex(3)> ["hello", "my", "friend"] |> Stream.map(&String.replace(&1, ~r{[aeiou]}, "_")) |> Enum.to_list
["h_ll_", "my", "fr__nd"]
Run Code Online (Sandbox Code Playgroud)

Dog*_*ert 9

您需要使用File.stream!开流模式一个文件,Stream.intoStream.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"
Run Code Online (Sandbox Code Playgroud)

编辑:作为@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"
Run Code Online (Sandbox Code Playgroud)

  • 您仍然想使用“Stream.into |> Stream.run”吗?由于“Enum”函数是急切的,而“Stream”函数是惰性的。 (3认同)
  • 我认为你也可以使用 `Enum.into` 而不是 `Stream.into |> Stream.run` (2认同)