codecamp

Elixir File模块

File模块中的函数让我们能够像打开IO设备一样打开文件.文件默认以二进制模式打开,需要使用IO模块中的IO.binread/2IO.binwrite/2函数进行读写:

iex> {:ok, file} = File.open "hello", [:write]
{:ok, #PID<0.47.0>}
iex> IO.binwrite file, "world"
:ok
iex> File.close file
:ok
iex> File.read "hello"
{:ok, "world"}

文件也可以以:utf8编码打开,它会告诉File模块将文件中读到的字节理解为UTF-8编码过的字节.

除了打开和读写文件之外,File模块还提供了许多文件操作函数.这些函数命名和UNIX中的相对应.例如,File.rm/1克英语删除文件,File.mkdir/1用于创建目录,File.mkdir_p/1用于创建目录和它所有的父目录.甚至还有File.cp_r/2File.rm_rf/1,用于目录递归地复制或删除文件(复制或删除目录中的内容).

你会发现File模块中的函数有两种形式:一种是"普通"形式,一种是带有感叹号(!)的形式.例如,例如,当我们在上面的例子中读取"hello"文件时,我们使用File.read/1.或者,我们可以使用File.read!/1:

iex> File.read "hello"
{:ok, "world"}
iex> File.read! "hello"
"world"
iex> File.read "unknown"
{:error, :enoent}
iex> File.read! "unknown"
** (File.Error) could not read file unknown: no such file or directory

注意到当文件不存在时,带!的版本抛出了一个错误.当你想要用模式匹配来处理不同的输入时最好使用不带!的版本:

case File.read(file) do
  {:ok, body}      -> # do something with the `body`
  {:error, reason} -> # handle the error caused by `reason`
end

然而,如果你期望文件在那儿,带感叹号的版本就更有用,因为它会抛出一个有意义的错误信息.不要这样写:

{:ok, body} = File.read(file)

当发生错误时,File.read/1会返回{:error, reason},模式匹配就会失败.你仍然会得到想要的结果(抛出错误),但信息会是模式不匹配(因此就不知道错误到底是什么了).

所以,如果你不想掌控错误,最好使用使用File.read!/1.

Elixir IO模块
Elixir Path模块
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

Elixir 基本操作符

Elixir 二进制,字符串和字符列表

Elixir 类型规格与行为

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }