本指南讨论如何使用 Lua 文件系统 库,通常简称为 LFS。
LFS 是一个强大的 Lua 库,它允许开发者执行普通 Lua 无法完成的常见文件系统操作 — 例如获取文件属性、创建和删除目录(文件夹)以及迭代目录中的文件。
想象一个“绘图”应用程序,允许用户创建并保存system.DocumentsDirectory
)。在这种情况下,跟踪用户在应用程序内部的操作相对容易,例如,通过维护已创建绘图的列表/数据库,并在图像文件添加到或从应用程序的文档目录中删除时更新它。
然而,对于更高级的功能,例如文件共享,用户可以导入和导出绘图,仅靠 Lua 本身是不够的。这就是 LFS 强大的地方。本质上,每次启动应用程序时,都可以使用 LFS 扫描 system.DocumentsDirectory
的内容并“检查”新的绘图。可以根据需要经常执行此操作,以确保准确地记录文件夹中的内容。
以下是如何使用 for
循环迭代应用程序文档目录内容的基本示例
local lfs = require( "lfs" ) local path = system.pathForFile( nil, system.DocumentsDirectory ) for file in lfs.dir( path ) do -- "file" is the current file or directory name print( "Found file or directory: " .. file ) end
如果应用程序下载外部资源(文件)并且这些文件必须以逻辑方式组织,则添加或删除目录绝对 ضروری。幸运的是,LFS 使这项任务变得简单
lfs.chdir()
设置新目录的目标位置local lfs = require( "lfs" ) local path = system.pathForFile( nil, system.DocumentsDirectory ) -- Change current working directory local success = lfs.chdir( path ) -- Returns boolean true on success
lfs.mkdir()
实际创建目录if success then lfs.mkdir( "MyNewFolder" ) end
local newFolderPath = lfs.currentdir() .. "/MyNewFolder"
如果需要删除目录,请使用现有的 os.remove() 函数,例如
local result, reason = os.remove( system.pathForFile( "MyNewFolder", system.DocumentsDirectory ) ) if result then print( "Directory removed!" ) else print( "Removal failed: " .. reason ) end
在某些情况下,可能需要定期检查某些文件的“上次修改”时间戳,尤其是在应用程序使用任何类型的同步功能时。时间戳也可用于跟踪用户上次读取特定文件的时间(但不一定更改了它)。
假设一个名为 mydata.txt
的文件位于 system.DocumentsDirectory
中。要设置用户上次读取文件的时间戳,请使用 LFS 触摸该文件。这样做会将时间戳设置为今天/现在。
local lfs = require( "lfs" ) local filePath = system.pathForFile( "mydata.txt", system.DocumentsDirectory ) -- "Touch" the file lfs.touch( filePath )
要查找文件的上次修改时间,可以访问 lfs.attributes
的 access
或 modification
属性
local lfs = require( "lfs" ) local filePath = system.pathForFile( "mydata.txt", system.DocumentsDirectory ) -- Get/print last modified time local fileAttributes = lfs.attributes( filePath ) print( "File last modified: " .. fileAttributes.modification )
返回的时间戳值将是自
LFS 非常强大,它可以完成比本指南中说明的更多功能。幸运的是,大多数 LFS 函数都简单易用。有关可用函数的完整列表以及每个函数的语法详细信息,请参阅LFS 参考。