system.pathForFile()

类型 函数
system.*
返回值 字符串
修订 版本 2024.3703
关键词 系统目录
另请参阅 读取和写入文件 (指南)
system.ApplicationSupportDirectory
system.CachesDirectory
system.DocumentsDirectory
system.ResourceDirectory
system.TemporaryDirectory

概述

使用系统定义的目录作为基准生成绝对路径。可选参数 `baseDirectory` 指定用于构造完整路径的基目录,其默认值为 `system.ResourceDirectory`。

此函数旨在与文件 I/O API 一起使用,**而不是**与需要 `baseDir` 或 `baseDirectory` 参数的显示/媒体 API 一起使用。

语法

system.pathForFile( filename [, baseDirectory] )
filename (必需)

字符串 文件的名称,或相对于 `baseDirectory` 的文件路径。或者,传递 `nil` 以获取 `baseDirectory` 的路径。

baseDirectory (可选)

常量 对应于文件所在基目录的常量。如果未提供参数,则默认值为 system.ResourceDirectory

注意事项

通用

如果基目录是 system.ResourceDirectory 并且生成的路径指向一个不存在的文件,则返回 `nil` 并在 Corona 模拟器控制台中显示警告消息。

Android 文件限制

Corona 中的文件访问基于底层操作系统,该操作系统因平台而异。在 iOS 设备上,您可以访问上述所有目录中的文件。但是,在 Android 上,没有字面意义上的 `system.ResourceDirectory`,因为所有资源文件都位于压缩的 `.apk` 文件中。

Corona 允许使用相应的 API 直接加载图像和音频文件,但它使用文件 I/O API 对 Android 上的资源文件的访问权限有限。具体来说,无法从资源目录读取以下类型:`.html`、`.htm`、`.3gp`、`.lua`、`.m4v`、`.mp4`、`.png`、`.jpg` 和 `.ttf`。

由于此限制,如果您需要将核心目录中捆绑的这些类型的文件复制到另一个目录,则必须更改文件名,以便文件 I/O API 可以访问它。例如,如果要将 `cat.png` 从资源目录移动到文档目录,则必须将其重命名为 `cat.png.txt` 才能复制。有关更多信息和示例,请参阅 读取和写入文件 指南。

示例

获取特定文件的路径
local path = system.pathForFile( "data.txt", system.DocumentsDirectory )
local fhd = io.open( path )
 
-- Determine if file exists
if fhd then
   print( "File exists" )
   fhd:close()
else
    print( "File does not exist!" )
end
获取基目录的路径
local path = system.pathForFile( nil, system.DocumentsDirectory )
print( path )