Cocos2dx 文件的读写

2020-09-19  本文已影响0人  游戏创作者

Cocos2dx-lua 文件读写例子:


local ChatDataCache = class("ChatDataCache")

function ChatDataCache:instance()
    if not self._instance then
        self._instance = ChatDataCache.new() 
    end
    
    return self._instance
end 

function ChatDataCache:ctor( ... )

    self._fileUtils = cc.FileUtils:getInstance()
    self.directory = device.writablePath .. device.directorySeparator.. "ChatCache"
    if not self._fileUtils:isDirectoryExist(self.directory) then
        self._fileUtils:createDirectory(self.directory)
    end

    print("+++++self.directory:",self.directory)
end

function ChatDataCache:saveFileByName( jsonStr,name )
    local fullPath = self.directory..device.directorySeparator..name..".json"

    if self._fileUtils:isFileExist(fullPath) then
        self._fileUtils:removeFile(fullPath)
    end

    local ok = self._fileUtils:writeStringToFile(jsonStr,fullPath)
    if ok then
        print("++++++++保存成功")
    end
end

function ChatDataCache:getFileDataByName( name )
    local fullPath = self.directory .. device.directorySeparator..name..".json"
    if self._fileUtils:isFileExist(fullPath) then
        local jsonStr = self._fileUtils:getStringFromFile(fullPath)
        local data = json.decode(jsonStr)
        return data
    end
    return {}
end

function ChatDataCache:getAllFile( ... )
    -- body
end

return ChatDataCache

这里用了cocos官方提供的 FileUtils 去读写文件的,他还提供了很多API,详细请看源码。

上一篇 下一篇

猜你喜欢

热点阅读