說明:本文所論述內容均基於cocos2dx 3.0 版本。
1、UserDefault
它是cocos2d-x用來存取基本數據類型用的。保存為XML文件格式。
查看CCUserDefault文件,可以看出,文件名默認為UserDefault.xml。在win32平台,Debug下,該文件在Debug.win32文件夾內。如果該文件不存在,則會創建新文件。
1 // root name of xml 2 #define USERDEFAULT_ROOT_NAME "userDefaultRoot" 3 4 #define XML_FILE_NAME "UserDefault.xml"
用UserDefault
操作方式比較簡單:
主要方法:(和java的map很像,鍵值對,應該很容易懂的)
1 void setBoolForKey(const char* pKey, bool value); 2 void setIntegerForKey(const char* pKey, int value); 3 void setFloatForKey(const char* pKey, float value); 4 void setDoubleForKey(const char* pKey, double value); 5 void setStringForKey(const char* pKey, const std::string & value);
通過鍵讀取數據,如果鍵不存在,可以設置一個defaultValue返回自己想要的值。
1 bool getBoolForKey(const char* pKey, bool defaultValue = false); 2 int getIntegerForKey(const char* pKey, int defaultValue = 0); 3 float getFloatForKey(const char* pKey, float defaultValue=0.0f); 4 double getDoubleForKey(const char* pKey, double defaultValue=0.0); 5 std::string getStringForKey(const char* pKey, const std::string & defaultValue = "");
UserDefault封裝了對XML文件的處理,提供了簡單操作文件的方法,但是不足之處在於固定的文件夾,固定的文件名稱。有限的數據類型。
2、FileUtils
static FileUtils* getInstance();//獲取FileUtils類的實例
在cocos2d-x中,文件讀寫其實直接使用c/c++中的文件讀寫操作方法,但是,在實際運用中,由於移動客戶端讀寫文件需要相應的權限,所以讀寫文件就需要先指定文件的路徑,我們不需要獲取絕對路徑,只需要獲取相對路徑就行,因為cocos2d-x底層已經做了相應各個平台的處理.
std::string fullPathForFilename(const std::string &filename);//獲取文件的完整路徑
std::string getStringFromFile(const std::string& filename);//讀取文件中的字符串
Data getDataFromFile(const std::string& filename);//獲取文件數據
可以看下Data類:
1 class CC_DLL Data 2 { 3 public: 4 static const Data Null; 5 //構造函數 6 Data(); 7 Data(const Data& other); 8 Data(Data&& other); 9 ~Data(); 10 // 重載符號 11 Data& operator= (const Data& other); 12 Data& operator= (Data&& other); 13 14 unsigned char* getBytes() const;//獲取數據 15 ssize_t getSize() const;//尺寸 16 void copy(unsigned char* bytes, const ssize_t size);//從bytes復制 17 void fastSet(unsigned char* bytes, const ssize_t size);//從bytes快速set,使用后bytes將不能在外部使用 18 void clear();//清除 19 bool isNull() const;//判空 20 private: 21 void move(Data& other); 22 private: 23 unsigned char* _bytes; 24 ssize_t _size; 25 };
unsigned char* getFileDataFromZip(const std::string& zipFilePath, const std::string& filename, ssize_t *size);//讀取壓縮文件數據(zip格式)
如果讀取成功size中會返回文件的大小,否則返回0。
如果我們通過setSearchPaths()設置搜索路徑("/mnt/sdcard/", "internal_dir/"),然后通過setSearchResolutionsOrder()設置子區分路徑("resources-ipadhd/", "resources-ipad/", "resources-iphonehd")。如果搜索文件名為'sprite.png' 那么會先在文件查找字典中查找key: sprite.png -> value: sprite.pvr.gz,然后搜索文件'sprite.pvr.gz'如下順序:
1 /mnt/sdcard/resources-ipadhd/sprite.pvr.gz (if not found, search next) 2 /mnt/sdcard/resources-ipad/sprite.pvr.gz (if not found, search next) 3 /mnt/sdcard/resources-iphonehd/sprite.pvr.gz (if not found, search next) 4 /mnt/sdcard/sprite.pvr.gz (if not found, search next) 5 internal_dir/resources-ipadhd/sprite.pvr.gz (if not found, search next) 6 internal_dir/resources-ipad/sprite.pvr.gz (if not found, search next) 7 internal_dir/resources-iphonehd/sprite.pvr.gz (if not found, search next) 8 internal_dir/sprite.pvr.gz (if not found, return "sprite.png")
If the filename contains relative path like "gamescene/uilayer/sprite.png",
and the mapping in fileLookup dictionary contains `key: gamescene/uilayer/sprite.png -> value: gamescene/uilayer/sprite.pvr.gz`.
The file search order will be:
/mnt/sdcard/gamescene/uilayer/resources-ipadhd/sprite.pvr.gz (if not found, search next)
/mnt/sdcard/gamescene/uilayer/resources-ipad/sprite.pvr.gz (if not found, search next)
/mnt/sdcard/gamescene/uilayer/resources-iphonehd/sprite.pvr.gz (if not found, search next)
/mnt/sdcard/gamescene/uilayer/sprite.pvr.gz (if not found, search next)
internal_dir/gamescene/uilayer/resources-ipadhd/sprite.pvr.gz (if not found, search next)
internal_dir/gamescene/uilayer/resources-ipad/sprite.pvr.gz (if not found, search next)
internal_dir/gamescene/uilayer/resources-iphonehd/sprite.pvr.gz (if not found, search next)
internal_dir/gamescene/uilayer/sprite.pvr.gz (if not found, return "gamescene/uilayer/sprite.png")
If the new file can't be found on the file system, it will return the parameter filename directly.
如果找到返回完整路徑,沒找到返回'sprite.png'。
void loadFilenameLookupDictionaryFromFile(const std::string &filename);//從文件導入文件名查找字典
文件為plist格式如下:
1 /** 2 * Loads the filenameLookup dictionary from the contents of a filename. 3 * 4 * @note The plist file name should follow the format below: 5 * 6 * @code 7 * <?xml version="1.0" encoding="UTF-8"?> 8 * <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> 9 * <plist version="1.0"> 10 * <dict> 11 * <key>filenames</key> 12 * <dict> 13 * <key>sounds/click.wav</key> 14 * <string>sounds/click.caf</string> 15 * <key>sounds/endgame.wav</key> 16 * <string>sounds/endgame.caf</string> 17 * <key>sounds/gem-0.wav</key> 18 * <string>sounds/gem-0.caf</string> 19 * </dict> 20 * <key>metadata</key> 21 * <dict> 22 * <key>version</key> 23 * <integer>1</integer> 24 * </dict> 25 * </dict> 26 * </plist> 27 * @endcode 28 * @param filename The plist file name. 29 * 30 @since v2.1 31 * @js loadFilenameLookup 32 * @lua loadFilenameLookup 33 */
void setFilenameLookupDictionary(const ValueMap& filenameLookupDict);//從ValueMap中設置文件名查找字典
ValueMap的定義:
1 typedef std::unordered_map<std::string, Value> ValueMap;
std::string fullPathFromRelativeFile(const std::string &filename, const std::string &relativeFile);//獲取相對應文件的完整路徑
e.g. filename: hello.png, pszRelativeFile: /User/path1/path2/hello.plist Return: /User/path1/path2/hello.pvr (If there a a key(hello.png)-value(hello.pvr) in FilenameLookup dictionary. )
void setSearchResolutionsOrder(const std::vector<std::string>& searchResolutionsOrder);//設置子搜索區分路徑
見fullPathForFilename()。
void addSearchResolutionsOrder(const std::string &order);//增加子搜索路徑
const std::vector<std::string>& getSearchResolutionsOrder();//獲取子搜索區分路徑
void setSearchPaths(const std::vector<std::string>& searchPaths);//設置搜索路徑
見fullPathForFilename()。
void addSearchPath(const std::string & path);//增加搜索路徑
const std::vector<std::string>& getSearchPaths() const;//獲取搜索路徑
std::string getWritablePath();//獲取一個可寫入文件的路徑
經過測試在win32平台上,debug版本返回的是程序文件所在的路徑,release返回的是“我的文檔”路徑。
bool isFileExist(const std::string& filePath);//判斷文件是否存在
經過測試在win32平台上,如果路徑中包含中文字符會找不到文件。所以可以自己寫個。
bool isAbsolutePath(const std::string& path);判斷是否為絕對路徑
void setPopupNotify(bool notify);
bool isPopupNotify();
Sets/Gets 當文件加載失敗時彈出messagebox.
ValueMap getValueMapFromFile(const std::string& filename);//從文件獲取ValueMap
bool writeToFile(ValueMap& dict, const std::string& fullPath);//寫入一個ValueMap數據到plist格式文件
ValueVector getValueVectorFromFile(const std::string& filename);//從文件獲取ValueVector
ValueVector定義:
1 typedef std::vector<Value> ValueVector;
函數也就這些了,還沒有寫demo代碼,寫好了貼過來。
3.SQLite
4、plist文件讀寫
在cocos2d-x中,對於plist文件,既可以讀取,也可以進行寫入的操作;下面先來看一個plist文件:

1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"/> 3 4 <plist version="1.0"> 5 <dict> 6 <key>string element key</key> 7 <string>string element value</string> 8 <key>array</key> 9 <array> 10 <dict> 11 <key>string in dictInArray key 0</key> 12 <string>string in dictInArray value 0</string> 13 <key>string in dictInArray key 1</key> 14 <string>string in dictInArray value 1</string> 15 </dict> 16 <string>string in array</string> 17 <array> 18 <string>string 0 in arrayInArray</string> 19 <string>string 1 in arrayInArray</string> 20 </array> 21 </array> 22 <key>dictInDict, Hello World</key> 23 <dict> 24 <key>string in dictInDict key</key> 25 <string>string in dictInDict value</string> 26 <key>bool</key> 27 <true/> 28 <key>integer</key> 29 <integer>1024</integer> 30 <key>float</key> 31 <real>1024.1024170</real> 32 <key>double</key> 33 <real>1024.1230000000000000</real> 34 </dict> 35 </dict> 36 </plist>
先不看上面的plist文件到底有些什么內容;實際上它是由下一段代碼生成的。

1 auto root = Dictionary::create(); 2 auto string = String::create("string element value"); 3 root->setObject(string, "string element key"); // 添加一個鍵值對 4 5 auto array = Array::create(); // 創建一個array 6 7 auto dictInArray = Dictionary::create(); 8 dictInArray->setObject(String::create("string in dictInArray value 0"), "string in dictInArray key 0"); 9 dictInArray->setObject(String::create("string in dictInArray value 1"), "string in dictInArray key 1"); 10 array->addObject(dictInArray); // 往數組中添加一個鍵值對 11 12 array->addObject(String::create("string in array")); // 往數組中添加一個字符串 13 14 auto arrayInArray = Array::create(); 15 arrayInArray->addObject(String::create("string 0 in arrayInArray")); 16 arrayInArray->addObject(String::create("string 1 in arrayInArray")); 17 array->addObject(arrayInArray); // 往數組中添加一個數組 18 19 root->setObject(array, "array"); 20 21 auto dictInDict = Dictionary::create(); 22 dictInDict->setObject(String::create("string in dictInDict value"), "string in dictInDict key"); 23 24 //add boolean to the plist 25 auto booleanObject = Bool::create(true); 26 dictInDict->setObject(booleanObject, "bool"); 27 28 //add interger to the plist 29 auto intObject = Integer::create(1024); 30 dictInDict->setObject(intObject, "integer"); 31 32 //add float to the plist 33 auto floatObject = Float::create(1024.1024f); 34 dictInDict->setObject(floatObject, "float"); 35 36 //add double to the plist 37 auto doubleObject = Double::create(1024.123); 38 dictInDict->setObject(doubleObject, "double"); 39 40 root->setObject(dictInDict, "dictInDict, Hello World"); 41 // end with / 42 std::string writablePath = FileUtils::getInstance()->getWritablePath(); 43 std::string fullPath = writablePath + "text.plist"; 44 if(root->writeToFile(fullPath.c_str())) 45 log("see the plist file at %s", fullPath.c_str()); 46 else 47 log("write plist file failed"); 48 49 // 讀取上面創建的內容 50 auto loadDict = __Dictionary::createWithContentsOfFile(fullPath.c_str()); 51 auto loadDictInDict = (__Dictionary*)loadDict->objectForKey("dictInDict, Hello World"); 52 auto boolValue = (__String*)loadDictInDict->objectForKey("bool"); 53 CCLOG("%s",boolValue->getCString()); 54 auto floatValue = (__String*)loadDictInDict->objectForKey("float"); 55 CCLOG("%s",floatValue->getCString()); 56 auto intValue = (__String*)loadDictInDict->objectForKey("integer"); 57 CCLOG("%s",intValue->getCString()); 58 auto doubleValue = (__String*)loadDictInDict->objectForKey("double"); 59 CCLOG("%s",doubleValue->getCString());
因此可以看出,對符合一定格式的plist文件,可以通過Dictionary進行操作。cocos2dx 3.0 的Dictionary,可以實現對Array,Dictionary,Integer,String,Bool等基礎數據類型進行讀寫。
下面再來看另一種讀取方式: 假定plist文件如下;

1 <plist version="1.0"> 2 <dict> 3 <key>name</key> 4 <string>Ls</string> 5 <key>isgirl</key> 6 <false/> 7 </dict> 8 </plist>
讀取方式二,這種方法是借助VectorMap來進行讀的:

1 FileUtils * fu = FileUtils::getInstance(); 2 ValueMap vm = fu->getValueMapFromFile("Info.plist"); 3 log("%s", vm["name"].asString().c_str()); // 讀取string -->Ls 4 bool bl = vm["isgirl"].asBool(); // 讀取bool -->0 5 log("%d", bl);
如果文件節點也是一個ValueMap,則可以通過xm["xx"].asValueMap()將節點轉換為ValueMap;如果根節點為數組也可能直接通過ValueVector.getValueVectorFromFile("xx")讀取數據;
5、xml文件讀取

1 FileUtils * fu = FileUtils::getInstance(); 2 auto doc = new tinyxml2::XMLDocument(); 3 doc->Parse(fu->getStringFromFile("data.xml").c_str()); 4 auto root = doc->RootElement(); 5 for (auto e = root->FirstChildElement(); e; e = e->NextSiblingElement()) { 6 std::string str; 7 for (auto attr = e->FirstAttribute(); attr; attr = attr->Next()) { 8 str += attr->Name(); 9 str += ":"; 10 str += attr->Value(); 11 str += ","; 12 } 13 log("%s", str.c_str()); 14 }
data.xml
1 <data> 2 <p name="zs" age="23"/> 3 <p name="ls" age="25"/> 4 </data>
上面的代碼輸出內容為:
cocos2d: name:zs,age:23,
cocos2d: name:ls,age:25,
注:需要導入cosos2d-x庫 <tinyxml2/tinyxml2.h>
6、JSON文件讀取
先來看一個json : [{"name": "zs","age": 23}, {"name": "ls","age": 25}]
1 rapidjson::Document d; 2 d.Parse<0>(fu->getStringFromFile("dj.json").c_str()); // 0表示默認的解析方式; 3 log("%s", d[rapidjson::SizeType(0)]["name"].GetString());
注:需要導入cocos2d-x庫 <json/document.h>