Corona中文站

强大、易学的跨平台(iOS/Android)开发框架。QQ群1:74390406(满) 群2:221929599

导航

分享在项目中用到的一个用于管理缓存文件的模块

Corona的lua源代码文件是不支持存放在子目录下的,目前我也没有找到在Document目录下创建子目录的方法,可以说corona在文件管理方面非常不方便。下面的代码的作用是

1)记录App从网络上下载的文件列表,防止重新下载。

2)清空列表内的缓存文件

主要的原理是,每次下载文件,都把文件名或者对应的ID写入到文件中(数据以JSON的格式保存),清空的时候,先去读取列表文件,根据里面记录的文件名和ID来删除文件。

--[[
    模块名称:物品缓存文件管理[itemsFileMgr.lua]

    功能说明:
        对存储物品信息的缓存文件进行管理

    创建者:XXX

    版本更新:
        [2011-08-06]创建了第一个版本

--]]
module(..., package.seeall)

local json = require "json"

local hasReadTab = false
local data = {}        --存储文件列表
local filename = "items.json"

--读取数据文件
function readData()
    local path = system.pathForFile( filename, system.DocumentsDirectory )
    local wfh = io.open(path, "r")
    local ret = ""
    if wfh then
        ret = wfh:read( "*a" )
        wfh:close()
    end
    --print("ret", ret)
    return ret
end

--添加新的物品ID(在下载新的物品时候后使用)
function addID( id, pic)
    if not hasRead then
        local s = readData()
        if string.len(s) > 0 then
            data = json.decode(s)
        end
    end

    if not data.ids then data.ids = {} end
    if not data.pics then data.pics = {} end

    if id then data.ids[#data.ids + 1] = id end
    if pic then data.pics[#data.pics + 1] = pic end


    local jsonData = json.encode(data)

    local path = system.pathForFile( filename, system.DocumentsDirectory )
    local wfh = io.open(path, "w+")

    if wfh then
        wfh:write( jsonData )
        wfh:flush()
        wfh:close()
    end
end

--清空所有的物品信息缓存文件
function clear()
    local destDir = system.DocumentsDirectory
    local OSremove = os.remove

    if not hasRead then
        local s = readData()
        if string.len(s) > 0 then
            data = json.decode(s)
        else
            viewAlert.show("緩存已全部清空")
        end
    end
    if data.ids then
        for k, v in ipairs(data.ids) do
            OSremove(system.pathForFile("item" .. tostring(v) .. ".txt", destDir))
        end
    end

    if data.pics then
        for k, v in ipairs(data.pics) do
            OSremove(system.pathForFile(tostring(v) .. ".png", destDir))
        end
    end

    common.clearTable(data)

    local path = system.pathForFile( filename, system.DocumentsDirectory )
    local wfh = io.open(path, "w+")

    if wfh then
        wfh:write( "" )
        wfh:flush()
        wfh:close()
    end

    --OSremove(system.pathForFile(filename, destDir))
end

 

<< Corona的中文排版-文本自动换行【附实例代码】网游从业者惊爆网游黑幕 MMORGP死期将至 >>

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

最近发表

Powered By Z-Blog 1.8 Walle Build 100427 Copyright 2011-2015 BuildApp.Net. All Rights Reserved.