Skip to content

文件方法

函数列表

1. 设置默认输入文件 (io.input)

说明: 设置默认输入文件

函数: io.input([file])

参数:

参数名类型说明
file字符串或文件句柄可以是文件名或文件句柄。如果省略,返回当前默认输入文件

返回值:

返回值类型说明
文件句柄如果带参数调用,返回文件句柄
文件句柄如果不带参数,返回当前默认输入文件

示例:

lua
-- 示例1: 设置默认输入文件
local filepath = getWorkPath() .. "/data.txt"
local file = io.open(filepath, "r")
if file then
    io.input(file)  -- 使用文件句柄
    print("当前输入文件:", io.input())
else
    print("文件不存在:", filepath)
end

-- 示例2: 直接通过文件名设置
local configPath = getWorkPath() .. "/config.txt"
io.input(configPath)  -- 直接使用文件名

-- 示例3: 获取当前默认输入文件
local current_input = io.input()
print("当前输入文件:", current_input)

-- 示例4: 读取默认输入文件的内容
local testPath = getWorkPath() .. "/test.txt"
io.input(testPath)
local content = io.read("*a")
print("文件内容:", content)

-- 示例5: 重置为标准输入
io.input(io.stdin)
print("已重置为标准输入")

2. 设置默认输出文件 (io.output)

说明: 设置默认输出文件

函数: io.output([file])

参数:

参数名类型说明
file字符串或文件句柄可以是文件名或文件句柄。如果省略,返回当前默认输出文件

返回值:

返回值类型说明
文件句柄如果带参数调用,返回文件句柄
文件句柄如果不带参数,返回当前默认输出文件

示例:

lua
-- 示例1: 设置默认输出文件
local outputPath = getWorkPath() .. "/output.txt"
local file = io.open(outputPath, "w")
if file then
    io.output(file)  -- 使用文件句柄
    print("当前输出文件:", io.output())
else
    print("创建文件失败:", outputPath)
end

-- 示例2: 直接通过文件名设置
local logPath = getWorkPath() .. "/log.txt"
io.output(logPath)  -- 直接使用文件名

-- 示例3: 获取当前默认输出文件
local current_output = io.output()
print("当前输出文件:", current_output)

-- 示例4: 向默认输出文件写入内容
local resultPath = getWorkPath() .. "/result.txt"
io.output(resultPath)
io.write("这是写入的内容\n")
io.write("当前时间: ", os.date(), "\n")
print("内容已写入:", resultPath)

-- 示例5: 重置为标准输出
io.output(io.stdout)
print("已重置为标准输出")

3. 从默认输入读取数据 (io.read)

说明: 从默认输入读取数据

函数: io.read(format1, format2, ...)

参数:

参数名类型说明
format字符串读取格式,可选值: "*a"读取整个文件, "*l"读取下一行(默认), "*n"读取一个数字, number读取指定字节数

返回值:

返回值类型说明
多种类型读取到的内容,多个格式时返回多个值

示例:

lua
-- 示例1: 从文件读取
local dataPath = getWorkPath() .. "/data.txt"
io.input(dataPath)

-- 读取整行
local line = io.read("*l")
print("第一行:", line)

-- 读取数字
local num = io.read("*n")
print("数字:", num)

-- 读取指定字节数
local bytes = io.read(10)
print("10个字节:", bytes)

-- 示例2: 从标准输入读取
print("请输入你的名字:")
local name = io.read("*l")
print("你好, " .. name)

print("请输入你的年龄:")
local age = io.read("*n")
print("年龄:", age)

-- 示例3: 多种格式同时读取
local valuesPath = getWorkPath() .. "/values.txt"
io.input(valuesPath)
local str, num1, num2 = io.read("*l", "*n", "*n")
print("字符串:", str, "数字1:", num1, "数字2:", num2)

-- 示例4: 读取整个文件
local docPath = getWorkPath() .. "/document.txt"
io.input(docPath)
local entire_content = io.read("*a")
print("文件全长:", #entire_content, "字符")

4. 向默认输出写入数据 (io.write)

说明: 向默认输出写入数据

函数: io.write(value1, value2, ...)

参数:

参数名类型说明
value1, value2, ...字符串或数字要写入的值,可以是字符串或数字

返回值: 无

示例:

lua
-- 示例1: 向文件写入
local outputPath = getWorkPath() .. "/output.txt"
io.output(outputPath)
io.write("这是第一行\n")
io.write("姓名: ", "李四", "\n")
io.write("年龄: ", 30, "\n")
io.write("成绩: ", 95.5, "\n")
print("数据已写入:", outputPath)

-- 示例2: 向标准输出写入(控制台)
io.output(io.stdout)
io.write("欢迎使用Lua程序\n")
io.write("当前时间: ", os.date(), "\n")
io.write("工作路径: ", getWorkPath(), "\n")

-- 示例3: 格式化输出
local name = "王五"
local score = 88.5
io.write(string.format("学生: %s, 分数: %.1f\n", name, score))

-- 示例4: 写入表格数据
local dataPath = getWorkPath() .. "/fruits.txt"
io.output(dataPath)
local data = {"苹果", "香蕉", "橙子"}
for i, fruit in ipairs(data) do
    io.write(i, ". ", fruit, "\n")
end
print("水果列表已写入:", dataPath)

-- 示例5: 大量数据写入
local bigDataPath = getWorkPath() .. "/bigdata.txt"
io.output(bigDataPath)
for i = 1, 100 do
    io.write("数据行 ", i, "\n")
end
print("大量数据已写入:", bigDataPath)

5. 迭代文件中的所有行 (io.lines)

说明: 迭代文件中的所有行

函数: io.lines([filename])

参数:

参数名类型说明
filename字符串可选,文件名。如果不提供,则从默认输入文件读取

返回值:

返回值类型说明
函数返回一个迭代器函数,每次调用返回下一行内容

示例:

lua
-- 示例1: 迭代特定文件
local dataPath = getWorkPath() .. "/data.txt"
print("文件内容:", dataPath)
local line_count = 0
for line in io.lines(dataPath) do
    line_count = line_count + 1
    print(line_count, ":", line)
end
print("总行数:", line_count)

-- 示例2: 设置默认输入文件后迭代
local configPath = getWorkPath() .. "/config.txt"
io.input(configPath)
for setting in io.lines() do
    print("配置:", setting)
end

-- 示例3: 处理每行数据
local numbersPath = getWorkPath() .. "/numbers.txt"
local sum = 0
local count = 0
for num_str in io.lines(numbersPath) do
    local num = tonumber(num_str)
    if num then
        sum = sum + num
        count = count + 1
    end
end
if count > 0 then
    print("平均值:", sum / count)
else
    print("没有找到有效数字")
end

-- 示例4: 过滤特定行
local logPath = getWorkPath() .. "/log.txt"
print("包含'error'的行:")
for line in io.lines(logPath) do
    if string.find(line, "error") then
        print("发现错误:", line)
    end
end

-- 示例5: 从标准输入读取多行(交互式)
print("请输入多行文本,以空行结束:")
for line in io.lines() do
    if line == "" then
        break
    end
    print("你输入了:", line)
end

6. 打开一个文件 (io.open)

说明: 打开一个文件

函数: io.open(path, mode)

参数:

参数名类型说明
path字符串文件路径
mode字符串打开模式,如"r"读模式, "w"写模式, "a"追加模式, "rb"二进制读模式等

返回值:

返回值类型说明
文件句柄成功时返回文件句柄
nil失败时返回nil
字符串失败时返回错误信息

示例:

lua
-- 示例1: 以读模式打开文件
local filepath = getWorkPath() .. "/data.txt"
local file, err = io.open(filepath, "r")
if file then
    -- 读取文件内容
    local content = file:read("*a")
    print("文件内容:", content)
    file:close()
else
    print("打开文件失败:", err)
end

-- 示例2: 以写模式打开文件
local outputPath = getWorkPath() .. "/output.txt"
local file2, err2 = io.open(outputPath, "w")
if file2 then
    file2:write("Hello World!\n")
    file2:write("这是写入的文本内容")
    file2:close()
    print("文件写入成功:", outputPath)
else
    print("打开文件失败:", err2)
end

-- 示例3: 以添加模式打开文件
local appendPath = getWorkPath() .. "/log.txt"
local file3, err3 = io.open(appendPath, "a")
if file3 then
    file3:write("\n这是追加的内容 - " .. os.date())
    file3:close()
    print("文件追加成功:", appendPath)
else
    print("打开文件失败:", err3)
end

-- 示例4: 逐行读取文件
local readPath = getWorkPath() .. "/data.txt"
local file4, err4 = io.open(readPath, "r")
if file4 then
    print("开始逐行读取文件:", readPath)
    for line in file4:lines() do
        print("行内容:", line)
    end
    file4:close()
else
    print("打开文件失败:", err4)
end

-- 示例5: 使用二进制模式读取文件
local binaryPath = getWorkPath() .. "/image.jpg"
local binaryFile, err5 = io.open(binaryPath, "rb")
if binaryFile then
    local binaryData = binaryFile:read("*a")
    print("二进制数据长度:", #binaryData)
    binaryFile:close()
else
    print("打开文件失败:", err5)
end

7. 读取文件所有内容 (readFile)

说明: 读取文件所有内容

函数: readFile(path)

参数:

参数名类型说明
path字符串文件绝对路径或者主资源文件中的文件名

返回值:

返回值类型说明
字符串读取的文件数据

示例:

lua
local path = getWorkPath().."/data.txt"
local ret = readFile(path)
print(ret)

8. 写字符串到文件 (writeFile)

说明: 写字符串到文件

函数: writeFile(path, str, [append])

参数:

参数名类型说明
path字符串文件绝对路径
str字符串要输入的字符串内容
append布尔值是否追加,可选参数

返回值:

返回值类型说明
booleantrue表示成功,false表示失败

示例:

lua
local path = getWorkPath().."/data.txt"
local ret = writeFile(path,"hello\n",true)
print(ret)

9. 获取文件大小 (fileSize)

说明: 获取文件大小

函数: fileSize(path)

参数:

参数名类型说明
path字符串文件绝对路径

返回值:

返回值类型说明
整数文件长度,单位是字节

示例:

lua
local path = getWorkPath().."/data.txt"
local ret = fileSize(path)
print(ret)

10. 文件或文件夹是否存在 (fileExist)

说明: 检查文件或文件夹是否存在

函数: fileExist(file)

参数:

参数名类型说明
file字符串文件绝对路径

返回值:

返回值类型说明
booleantrue表示存在,false表示不存在

示例:

lua
local path = getWorkPath().."/data.txt"
print(fileExist(path))

11. 创建文件夹 (mkdir)

说明: 创建文件夹

函数: mkdir(dir)

参数:

参数名类型说明
dir字符串文件夹绝对路径

返回值:

返回值类型说明
booleantrue表示成功,false表示失败

示例:

lua
local path = getWorkPath().."/mydir"
print(mkdir(path))

12. 删除文件或文件夹 (delfile)

说明: 删除文件或文件夹

函数: delfile(dir)

参数:

参数名类型说明
dir字符串文件夹绝对路径

返回值:

返回值类型说明
booleantrue表示成功,false表示失败

示例:

lua
local path = getWorkPath().."/data.txt"

writeFile(path,"hello")

if fileExist(path) then
	print(path.." 存在了")
	delfile(path)
end

if fileExist(path) == false then
	print(path.." 不存在了")
end
sleep(100000)

13. 列出目录内容 (listDir)

说明: 列出目录内容

函数: listDir(path)

参数:

参数名类型说明
path字符串要列出的目录路径

返回值:

返回值类型说明
表(table)返回一个表,包含指定目录下的所有文件和子目录名称。如果目录不存在或无法访问,返回空表

示例:

lua
-- 示例1: 列出工作目录下的所有文件和文件夹
local workPath = getWorkPath()
local fileList = listDir(workPath)

print("工作目录内容:")
for i, filename in ipairs(fileList) do
    print(i .. ": " .. filename)
end

-- 示例2: 列出特定子目录内容
local subDir = getWorkPath() .. "/images"
local imageFiles = listDir(subDir)

if #imageFiles > 0 then
    print("图片文件列表:")
    for i, imgName in ipairs(imageFiles) do
        print("  " .. imgName)
    end
else
    print("目录为空或不存在: " .. subDir)
end

-- 示例3: 过滤特定类型的文件
local scriptDir = getWorkPath() .. "/scripts"
local allFiles = listDir(scriptDir)
local luaFiles = {}

for i, filename in ipairs(allFiles) do
    if string.match(filename, "%.lua$") then
        table.insert(luaFiles, filename)
    end
end

print("Lua脚本文件:")
for i, luaFile in ipairs(luaFiles) do
    print("  " .. luaFile)
end

-- 示例4: 统计目录信息
local targetDir = getWorkPath() .. "/documents"
local contents = listDir(targetDir)

local fileCount = #contents
local folderCount = 0
local fileSize = 0

-- 简单的文件夹检测(通过扩展名判断,实际应用中可能需要更复杂的方法)
for i, name in ipairs(contents) do
    if not string.match(name, "%.") then
        folderCount = folderCount + 1
    end
end

print("目录统计:")
print("  总项目数: " .. fileCount)
print("  文件夹数: " .. folderCount)
print("  文件数: " .. (fileCount - folderCount))

-- 示例5: 递归列出所有子目录(简单版本)
function listAllDirs(basePath, level)
    level = level or 0
    local indent = string.rep("  ", level)
    local items = listDir(basePath)
    
    for i, item in ipairs(items) do
        local fullPath = basePath .. "/" .. item
        print(indent .. item)
        
        -- 简单判断是否为目录(无扩展名)
        if not string.match(item, "%.") then
            listAllDirs(fullPath, level + 1)
        end
    end
end

print("目录树:")
listAllDirs(getWorkPath())

-- 示例6: 检查目录是否为空
function isDirectoryEmpty(path)
    local contents = listDir(path)
    return #contents == 0
end

local testDir = getWorkPath() .. "/temp"
if isDirectoryEmpty(testDir) then
    print("目录为空: " .. testDir)
else
    print("目录包含文件: " .. testDir)
end

-- 示例7: 查找特定文件
function findFile(directory, pattern)
    local files = listDir(directory)
    local results = {}
    
    for i, filename in ipairs(files) do
        if string.match(filename, pattern) then
            table.insert(results, filename)
        end
    end
    
    return results
end

local configFiles = findFile(getWorkPath(), "^config.*%.lua$")
print("找到的配置文件:")
for i, configFile in ipairs(configFiles) do
    print("  " .. configFile)
end

14. 释放资源到指定目录 (extractAssets)

说明: 释放资源到指定目录

函数: extractAssets(assets, outdir, pattern)

参数:

参数名类型说明
assets字符串资源文件名
outdir字符串输出目录
pattern字符串文件匹配模式,如"*.bmp"

返回值: 无

示例:

lua
--把资源中的bmp位图文件释放到/data/temp目录中
local outpath = getWorkPath()
extractAssets("test.rc",outpath,"*.bmp")

15. 压缩文件或者文件夹 (zip)

说明: 压缩文件或者文件夹

函数: zip(file, saveZip, [containroot])

参数:

参数名类型说明
file字符串待压缩的文件或者文件夹
saveZip字符串压缩文件绝对路径
containroot布尔值是否包含父目录,默认不填写为true表示包含,可选参数

返回值:

返回值类型说明
booleantrue表示成功,false表示失败

示例:

lua
local work = getWorkPath() .. "/test.png"
local saveZip = getWorkPath() .. "/test.zip"
zip(work,saveZip)

16. 解压zip文件 (unZip)

说明: 解压zip文件到指定的目录

函数: unZip(zippath, outdir, [pass], [charset])

参数:

参数名类型说明
zippath字符串zip文件路径
outdir字符串解压输出目录
pass字符串密码,可选参数
charset字符串字符编码,可选参数

返回值:

返回值类型说明
booleantrue表示成功,false表示失败

示例:

lua
local save = getWorkPath() .. "/mysave"
local zippath = getWorkPath() .. "/test.zip"
local ret = unZip(zippath,save)
print(ret)