首页 > 代码库 > Cocos2d-x3.1FileUtilsTest使用

Cocos2d-x3.1FileUtilsTest使用

Cocos2d-x3.1中FileUtils的使用:本使用教程是基于HelloWorld的。仅仅需在HelloWorld的init()函数中加入例如以下代码

//头文件
#include "platform/CCFileUtils.h"//FileUtils头文件
#include <stdio.h>//使用文件操作
#include "deprecated/CCDictionary.h"//字典类
//下面各Test依次运行
//Test1:TestResolutionDirectories測试解决方式文件夹
//    auto sharedFileUtils = FileUtils::getInstance();//创建单例对象
//    std::string ret;
//    sharedFileUtils->purgeCachedEntries();//清理文件,查找缓存
//    auto _defaultSearchPathArray = sharedFileUtils->getSearchPaths();//获取一组查找路径,返回数组类型
//    std::vector<std::string> searchPaths = _defaultSearchPathArray;
//    searchPaths.insert(searchPaths.begin(),   "Misc");//加入查找路径
//    sharedFileUtils->setSearchPaths(searchPaths);//设置查找路径。能够是相对路径,也但是绝对路径
//    //<span style="font-family: Roboto, sans-serif; font-size: 14px; line-height: 22px;">获取包括资源查找顺序的array</span>
//    auto _defaultResolutionsOrderArray = sharedFileUtils->getSearchResolutionsOrder();
//    std::vector<std::string> resolutionsOrder = _defaultResolutionsOrderArray;
//    //插入查找顺序
//    resolutionsOrder.insert(resolutionsOrder.begin(), "resources-ipadhd");
//    resolutionsOrder.insert(resolutionsOrder.begin()+1, "resources-ipad");
//    resolutionsOrder.insert(resolutionsOrder.begin()+2, "resources-widehd");
//    resolutionsOrder.insert(resolutionsOrder.begin()+3, "resources-wide");
//    resolutionsOrder.insert(resolutionsOrder.begin()+4, "resources-hd");
//    resolutionsOrder.insert(resolutionsOrder.begin()+5, "resources-iphone");
//    //<span style="font-family: Roboto, sans-serif; font-size: 14px; line-height: 22px;">设置包括资源查找路径的array</span>
//    sharedFileUtils->setSearchResolutionsOrder(resolutionsOrder);
//    
//    for(int i = 1; i < 7; i++)
//    {
//        auto filename = String::createWithFormat("test%d.txt",i);
//        ret = sharedFileUtils->fullPathForFilename(filename->getCString());//查找资源路径
//        log("%s -> %s",filename->getCString(),ret.c_str());//打印资源路径
//    }
    
    
//Test2:TestSearchPath 測试寻找路径
//    auto sharedFileUtils = FileUtils::getInstance();
//    std::string ret;
//    sharedFileUtils->purgeCachedEntries();
//    auto _defaultSearchPathArray = sharedFileUtils->getSearchPaths();
//    std::vector<std::string> searchPaths = _defaultSearchPathArray;
//    std::string writablePath = sharedFileUtils->getWritablePath();//改行以上同上
//    std::string fileName = writablePath + "external.txt";//设置可写文件路径
//    char szBuf[100] = "Hello Cocos2d-x";//写的内容
//    FILE* fp = fopen(fileName.c_str(), "wb");//打开路径下得文件
//    if(fp)
//    {
//        size_t ret = fwrite(szBuf, 1, strlen(szBuf), fp);//写过程
//        CCASSERT(ret != 0, "fwrite function returned zero value");//断言
//        fclose(fp);
//        if (ret != 0) {
//            log("Writing file to writable path succeed.");
//        }
//    }
//    //加入查找路径
//    searchPaths.insert(searchPaths.begin(), writablePath);
//    searchPaths.insert(searchPaths.begin()+1, "Misc/searchpath1");
//    searchPaths.insert(searchPaths.begin()+2, "Misc/searchpath2");
//    sharedFileUtils->setSearchPaths(searchPaths);//设置查找路径
//    //<span style="font-family: Roboto, sans-serif; font-size: 14px; line-height: 22px;">获取包括资源查找顺序的array</span>
//    auto _defaultResolutionsOrderArray = sharedFileUtils->getSearchResolutionsOrder();
//    std::vector<std::string> resolutionsOrder = _defaultResolutionsOrderArray;
//    resolutionsOrder.insert(resolutionsOrder.begin(), "resources-ipad");//插入查找顺序
//    sharedFileUtils->setSearchResolutionsOrder(resolutionsOrder);//设置查找顺序
//
//    for(int i = 1; i < 3; i++)
//    {
//        auto filename = String::createWithFormat("file%d.txt",i);//同上
//        ret = sharedFileUtils->fullPathForFilename(filename->getCString());
//        log("%s -> %s",filename->getCString(),ret.c_str());
//    }
//    
//    std::string fullPath = sharedFileUtils->fullPathForFilename("external.txt");
//    log("external.txt file path = %s",fullPath.c_str());
//    if (fullPath.length() > 0) {
//        fp = fopen(fullPath.c_str(), "rb");
//        if(fp)
//        {
//            char szReadBuf[100] = {0};
//            size_t read = fread(szReadBuf, 1, strlen(szBuf), fp);//读上面写成功的文件
//            if(read > 0)
//                log("The content of file from writeable path:%s",szReadBuf);
//            fclose(fp);
//        }
//    }
    
//Test3:TestFilenameLookup
//    auto sharedFileUtils = FileUtils::getInstance();
//    
//    ValueMap dict;//ValueMap类型,相似于C++的Map,键值对
//    dict["grossini.bmp"] = Value("CloseNormal.png");
//    dict["grossini.xcf"] = Value("CloseSelected.png");
//    //<span style="font-family: Roboto, sans-serif; font-size: 14px; line-height: 22px;">设置文件查找词典,參数是替代文件名称的字典</span>
//    sharedFileUtils->setFilenameLookupDictionary(dict);
//    
//    // Instead of loading carlitos.xcf, it will load grossini.png
//    auto sprite = Sprite::create("grossini.xcf");
//    this->addChild(sprite);
//    
//    auto s = Director::getInstance()->getWinSize();
//    sprite->setPosition(Vec2(s.width/2, s.height/2));

//Test4:TestIsFileExist  測试文件是否存在
//    auto s = Director::getInstance()->getWinSize();
//    auto sharedFileUtils = FileUtils::getInstance();
//    
//    Label* pTTF = nullptr;
//    bool isExist = false;
//    
//    isExist = sharedFileUtils->isFileExist("CloseSelected.png");
//    
//    pTTF = Label::createWithSystemFont(isExist ?

"CloseSelected.png exists" : "CloseSelected.png doesn‘t exist", "", 20); // pTTF->setPosition(Vec2(s.width/2, s.height/3)); // this->addChild(pTTF); // // isExist = sharedFileUtils->isFileExist("CloseNormal.png"); // pTTF = Label::createWithSystemFont(isExist ?

"CloseNormal.png exists" : "CloseNormal.png doesn‘t exist", "", 20);//条件语句 // pTTF->setPosition(Vec2(s.width/2, s.height/3*2)); // this->addChild(pTTF); //Test5:TextWritePlist 写Plist文件 auto root = __Dictionary::create();//创建一个字典类对象 auto string = __String::create("string element value");//创建一个String类对象 root->setObject(string, "string element key");//root加入string类型键值对 auto array = __Array::create();//创建一个Array对象 auto dictInArray = __Dictionary::create();//创建一个字典类对象 dictInArray->setObject(__String::create("string in dictInArray value 0"), "string in dictInArray key 0");//为字典类对象加入键值对 dictInArray->setObject(__String::create("string in dictInArray value 1"), "string in dictInArray key 1"); array->addObject(dictInArray);//将字典类对象加入到数组 array->addObject(String::create("string in array"));//将String对象加入到数组 auto arrayInArray = __Array::create();//创建Array类对象 arrayInArray->addObject(__String::create("string 0 in arrayInArray"));//为Array类对象加入成员 arrayInArray->addObject(__String::create("string 1 in arrayInArray")); array->addObject(arrayInArray);//将Array对象加入到array对象 root->setObject(array, "array");//root加入Array类键值对 auto dictInDict = __Dictionary::create();//创建字典类对象 dictInDict->setObject(__String::create("string in dictInDict value"), "string in dictInDict key");//加入键值对 //add boolean to the plist auto booleanObject = Bool::create(true);//创建Bool对象 dictInDict->setObject(booleanObject, "bool");//加入Bool类型键值对 //add interger to the plist auto intObject = Integer::create(1024); dictInDict->setObject(intObject, "integer");//加入Integer类型键值对 //add float to the plist auto floatObject = Float::create(1024.1024f); dictInDict->setObject(floatObject, "float");//加入float类型键值对 //add double to the plist auto doubleObject = Double::create(1024.123);//加入double类型键值对 dictInDict->setObject(doubleObject, "double"); root->setObject(dictInDict, "dictInDict, Hello World");//root加入字典类键值对 // end with / std::string writablePath = FileUtils::getInstance()->getWritablePath(); std::string fullPath = writablePath + "text.plist"; //将plist文件写入到路径下得文件里 if(root->writeToFile(fullPath.c_str())) log("see the plist file at %s", fullPath.c_str()); else log("write plist file failed"); // //创建TTF,显示plist文件路经 auto label = Label::createWithTTF(fullPath.c_str(), "Thonburi.ttf", 30); this->addChild(label); auto winSize = Director::getInstance()->getWinSize(); label->setPosition(Vec2(winSize.width/2, winSize.height/3)); //<span style="font-family: Roboto, sans-serif; font-size: 14px; line-height: 22px;">依据plist文件创建一个dictionary.</span> auto loadDict = __Dictionary::createWithContentsOfFile(fullPath.c_str());

    //依据键值。读取Dictionary的值,然后依据键再读取里面的值
    auto loadDictInDict = (__Dictionary*)loadDict->objectForKey("dictInDict, Hello World");
    auto boolValue = http://www.mamicode.com/(__String*)loadDictInDict->objectForKey("bool");
    CCLOG("%s",boolValue->getCString());//控制台打印
    auto floatValue = http://www.mamicode.com/(__String*)loadDictInDict->objectForKey("float");
    CCLOG("%s",floatValue->getCString());
    auto intValue = http://www.mamicode.com/(__String*)loadDictInDict->objectForKey("integer");
    CCLOG("%s",intValue->getCString());
    auto doubleValue = http://www.mamicode.com/(__String*)loadDictInDict->objectForKey("double");
    CCLOG("%s",doubleValue->getCString());

很多其它关于__Dictionary以及FileUtils可參考Cocos2d-x的API文档

http://cn.cocos2d-x.org/doc/cocos2d-x-3.0/d0/d1a/classcocos2d_1_1_____dictionary.html#a9b09179c67f6919b779b9aa656274e33

Cocos2d-x3.1FileUtilsTest使用