Lua 文件系统 (LFS)

本指南讨论如何使用 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 使这项任务变得简单

  1. 首先,使用 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
  1. 接下来,使用 lfs.mkdir() 实际创建目录
if success then
    lfs.mkdir( "MyNewFolder" )
end
  1. 最后,如果需要,将新目录的路径存储在变量中
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.attributesaccessmodification 属性

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 )
注意

返回的时间戳值将是自1970年1月1日午夜以来的秒数。有关 Solar2D 中时间和日期的更多信息,请参阅使用时间和日期教程。

更多参考

LFS 非常强大,它可以完成比本指南中说明的更多功能。幸运的是,大多数 LFS 函数都简单易用。有关可用函数的完整列表以及每个函数的语法详细信息,请参阅LFS 参考