文件方法
## 打开一个文件输入
| 函数名 | 返回值 | 备注 |
| ------------ | -------- | -------------------- |
| io.input([file]) | | 返回定时器剩余时间 |
| **参数名** | **类型** | |
| 文件路径 | 字符串 | 可以是字符串路径也可以是以io.open打开的句柄 |
用文件名调用它时,(以文本模式)来打开该名字的文件,
并将文件句柄设为默认输入文件.如果用文件句柄去调用它,
就简单的将该句柄设为默认输入文件.如果调用时不传参数,它返回当前的默认输入文件
返回值:文件句柄,在出错的情况下,函数抛出错误而不是返回错误码
方法例子 --文件名
``` Lua
io.input("/mnt/sdcard/test.txt")
print(io.read("*a"))
io:close()
```
--文件句柄(需要使用可读模式)
```Lua
local file = io.open("/mnt/sdcard/test.txt", "r")
print(io.input(file))
print(io.read("*a"))
print(file)
io.close()
```
## 循环迭代器遍历
| 函数名 | 返回值 | 备注 |
| ------------ | -------- | -------------------- |
| io.lines([file]) | | 返回定时器剩余时间 |
| **参数名** | **类型** | |
| 文件路径 | 字符串 | 字符串路径 |
提供一个循环迭代器以遍历文件,
如果指定了文件名则当遍历结束后将自动关闭该文件;
若使用默认文件,则遍历结束后不会自动关闭文件。
方法例子
``` Lua
for line in io.lines("/mnt/sdcard/test.txt") do
print(line)
end
```
## 打开一个文件
方法介绍 方法名称:打开一个文件 语法:io.open(path,mode) 参数说明 path:字符串类型表示要打开的文件路径 mode:文件打开的模式,如下 "r": 读模式 (默认); "w": 写模式;\r\na: 添加模式; "r+": 更新模式,所有之前的数据将被保存 "w+": 更新模式,所有之前的数据将被清除 "a+": 添加更新模式,所有之前的数据将被保存,只允许在文件尾进行添加 "b": 某些系统支持二进制方式 返回值:文件句柄,失败则返回nil+错误信息 方法例子 local file = io.open("/mnt/sdcard/test.txt", mode) print(file:write("123", "a")) file:close() local file = io.open("/mnt/sdcard/test.txt", "r+") print(file:read("*a")) file:close()
## 打开一个文件输出
方法介绍 方法名称:打开一个文件输出 语法:io.output([file]) 参数说明 file:可以是字符串路径也可以是以io.open打开的句柄 用文件名调用它时,以文本模式来打开该名字的文件, 并将文件句柄设为默认输出文件.如果用文件句柄去调用它, 就简单的将该句柄设为默认输出文件.如果调用时不传参数, 它返回当前的默认输出文件.在出错的情况下,函数抛出错误而不是返回错误码。
方法例子 print(io.output("/mnt/sdcard/test.txt")) io.write("123") io.close()
## 读取文件数据
方法介绍 方法名称:读取文件数据 语法:io.read() 等价于 io.input():read(···) 方法例子 io.input("/mnt/sdcard/test.txt") while true do local ReadContent = io.read() if ReadContent == null then break end print(ReadContent) end io.close()
## 写入数据到文件
方法介绍 方法名称:写入数据到文件 语法:io.read() 等价于 io.output():write(···) 方法例子 io.output("/mnt/sdcard/test.txt") io.write(tostring("123")) io.close()