Cocos2d-x3.1FileUtilsTest使用

Cocos2d-x3.1中FileUtils的使用:本使用教程是基於HelloWorld的。僅僅需在HelloWorld的init()函數中加入例如如下代碼html

//頭文件
#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 = (__String*)loadDictInDict->objectForKey("bool");
    CCLOG("%s",boolValue->getCString());//控制檯打印
    auto floatValue = (__String*)loadDictInDict->objectForKey("float");
    CCLOG("%s",floatValue->getCString());
    auto intValue = (__String*)loadDictInDict->objectForKey("integer");
    CCLOG("%s",intValue->getCString());
    auto doubleValue = (__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
iphone

相關文章
相關標籤/搜索