如何寻找适合在Corona中进行读/写操作的文件,或者将文件放在哪里?

以下是Peach Ellen的 ego.lua 文件,它读取和写入文件。但是,我不确定在哪里放置我的 txt 文件才能读取和写入它。我将文件放入项目文件中,并将其拖入 Corona 中的项目中。但是,它对更改没有反应。

module (..., package.seeall)

--保存函数
function saveFile( fileName, fileData )
  --文件路径
  local path = system.pathForFile( fileName, system.DocumentsDirectory )
  --打开文件
  local file = io.open( path, "w+" )

  --保存指定的值到文件中
  if file then
    file:write( fileData )
    io.close( file )
  end
end

--加载函数
function loadFile( fileName )
  --文件路径
  local path = system.pathForFile( fileName, system.DocumentsDirectory )
  --打开文件
  local file = io.open( path, "r" )

  --如果文件存在,则返回数据
  if file then
    local fileData = file:read( "*a" )
    io.close( file )
    return fileData
  --如果文件不存在,则创建并写入 "empty"
  else
    file = io.open( path, "w" )
    file:write( "empty" )
    io.close( file )
    return "empty"
  end
end

这是使用 ego.lua 的 main.lua 文件,它尝试记录最高分:

--隐藏状态栏
display.setStatusBar(display.HiddenStatusBar)

--保存/加载记录
local ego = require "ego"
local saveFile = ego.saveFile
local loadFile = ego.loadFile

--创建背景并使其变成蓝色
local bg = display.newRect( 0, 0, 320, 480 )
bg:setFillColor( 150, 180, 200 )

--将分数初始化为0
local score = 0

--创建分数文本并将其设置为深灰色
local scoreText = display.newText(score, 200, 20, native.systemFont, 24)
scoreText:setTextColor( 80, 80, 80 )

--将分数加一并更新分数文本的函数
local function addToScore()
  score = score + 1
  scoreText.text = score
end
bg:addEventListener("tap", addToScore)

--从文件加载高分值(它最初将是一个字符串)
highscore = loadFile ("gameScores.txt")

--如果文件为空(这意味着这是您第一次运行应用程序),请将其保存为 0
local function checkForFile ()
  if highscore == "empty" then
    highscore = 0
    saveFile("gameScores.txt", highscore)
  end
end
checkForFile()

--打印当前的高分值
print ("Highscore is", highscore)

--当应用程序退出(或模拟器刷新)时,保存新的高分值
--(如果分数>高分数,数据将不会更改)
local function onSystemEvent ()
  if score > tonumber(highscore) then --我们使用 tonumber,因为 highscore 在加载时是字符串
    saveFile("gameScores.txt", score)
  end
end

Runtime:addEventListener( "system", onSystemEvent )
点赞
用户1137788
用户1137788

你可以看到 Ego 类将所有的文件都存储在 system.DocumentsDirectory 目录中。

可以通过文件 --> 显示项目沙盒 --> 文档访问该目录。

如果你想的话,你可以将目录更改为其他目录。可用的目录有:

system.ResourceDirectory

system.DocumentsDirectory

system.TemporaryDirectory

system.CachesDirectory

2012-06-25 16:15:21