| 版权声明:本文为博主原创文章,未经博主允许不得转载。
FileUtils
在游戏中,用户要保存自己的偏好设置和玩家的信息,都需要涉及到游戏数据的处理。首先要想处理数据,则要找到文件,创建文件,读写文件...;在Cocos2d-x中有一个类FileUtils,FileUtils是Cocos2d-x引擎中封装的一个简单的文件操作类,该类几乎实现了所有文件操作的功能,类FileUtils并不只是一个文件,也不是两个文件。在每个平台都会有一个FileUtils的头文件和实现文件。在游戏的开始阶段,游戏的文件资源一般都是存放在硬盘中,在游戏开始的时候,文件操作模块就会将硬盘中的资源转移到内存中。
在游戏中文件的读取分为三个部分:
1. 资源存放在硬盘中
2. 资源存放在内存中
3. 资源存放在缓存中
API常用函数介绍:
1 /** Gets the instance of FileUtils.获得文件模块的单例对象 */ 2 static FileUtils* getInstance(); 3 /** Destroys the instance of FileUtils.释放文件模块*/ 4 static void destroyInstance(); 5 /** 清空缓存 6 * Purges full path caches. 7 */ 8 virtual void purgeCachedEntries(); 9 /** 从文件中获取字符串。 10 * Gets string from a file. 11 */ 12 virtual std::string getStringFromFile(const std::string& filename); 13 /** 获得资源文件的内容 14 * Creates binary data from a file. 15 * @return A data object. 16 */ 17 virtual Data getDataFromFile(const std::string& filename); 18 /** 获取资源文件数据 19 * Gets resource file data 20 * @param[in] filename The resource file name which contains the path. 21 * @param[in] mode The read mode of the file. 22 * @param[out] size If the file read operation succeeds, it will be the data size, otherwise 0. 23 * @return Upon success, a pointer to the data is returned, otherwise NULL. 24 * @warning Recall: you are responsible for calling free() on any Non-NULL pointer returned. 25 */ 26 CC_DEPRECATED_ATTRIBUTE virtual unsigned char* getFileData(const std::string& filename, const char* mode, ssize_t *size); 27 /** 从zip文件中获得资源文件的内容 28 * Gets resource file data from a zip file. 29 * @param[in] filename The resource file name which contains the relative path of the zip file. 30 * @param[out] size If the file read operation succeeds, it will be the data size, otherwise 0. 31 * @return Upon success, a pointer to the data is returned, otherwise nullptr. 32 * @warning Recall: you are responsible for calling free() on any Non-nullptr pointer returned. 33 */ 34 virtual unsigned char* getFileDataFromZip(const std::string& zipFilePath, const std::string& filename, ssize_t *size); 35 /** 获得一个文件的绝对路径,返回值为文件的绝对路径(通过文件名查找文件,并将它所在的路径返回) 36 * Returns the fullpath for a given filename. 37 */ 38 virtual std::string fullPathForFilename(const std::string &filename) const; 39 /** 通过一个文件名在字典容器中查找文件 40 * Loads the filenameLookup dictionary from the contents of a filename. 41 * @note The plist file name should follow the format below: 42 */ 43 virtual void loadFilenameLookupDictionaryFromFile(const std::string &filename); 44 /** 设置一个按文件名查找的字典。 45 * Sets the filenameLookup dictionary. 46 * @param pFilenameLookupDict The dictionary for replacing filename. 47 */ 48 virtual void setFilenameLookupDictionary(const ValueMap& filenameLookupDict); 49 /** 获得一个文件的绝对路径包含文件名 50 * Gets full path from a file name and the path of the relative file. 51 */ 52 virtual std::string fullPathFromRelativeFile(const std::string &filename, const std::string &relativeFile); 53 /** 设置数组容器内所包含的资源的搜索顺序。 54 * Sets the array that contains the search order of the resources. 55 * @param searchResolutionsOrder The source array that contains the search order of the resources. 56 * @see getSearchResolutionsOrder(), fullPathForFilename(const char*). 57 */ 58 virtual void setSearchResolutionsOrder(const std::vector<std::string>& searchResolutionsOrder); 59 /** 追加资源的搜索顺序。 60 * Append search order of the resources. 61 * @see setSearchResolutionsOrder(), fullPathForFilename(). 62 */ 63 virtual void addSearchResolutionsOrder(const std::string &order,const bool front=false); 64 /** 获取数组中所包含的资源的搜索顺序 65 * Gets the array that contains the search order of the resources. 66 * @see setSearchResolutionsOrder(const std::vector<std::string>&), fullPathForFilename(const char*). 67 */ 68 virtual const std::vector<std::string>& getSearchResolutionsOrder() const; 69 /** 设置资源路径 70 * Sets the array of search paths. 71 */ 72 virtual void setSearchPaths(const std::vector<std::string>& searchPaths); 73 /** 设置默认资源的根路径。 74 * Set default resource root path. 75 */ 76 void setDefaultResourceRootPath(const std::string& path); 77 /** 添加搜索路径。 78 * Add search path. 79 */ 80 void addSearchPath(const std::string & path, const bool front=false); 81 /** 获取的搜索路径的数组。 82 * Gets the array of search paths. 83 */ 84 virtual const std::vector<std::string>& getSearchPaths() const; 85 /** 获取可写的路径。 86 * Gets the writable path. 87 * @return The path that can be write/read a file in 88 */ 89 virtual std::string getWritablePath() const = 0; 90 /** 设置可写的路径。 91 * Sets writable path. 92 */ 93 virtual void setWritablePath(const std::string& writablePath); 94 /** 设置在无法加载图像时候是否弹出一个消息框。 95 * Sets whether to pop-up a message box when failed to load an image. 96 */ 97 virtual void setPopupNotify(bool notify); 98 /** 检查在无法加载图像的时候是否弹出一个消息框。 99 * Checks whether to pop up a message box when failed to load an image. 100 * @return True if pop up a message box when failed to load an image, false if not. 101 */ 102 virtual bool isPopupNotify() const; 103 /** 文件到ValueMap的内容转换。(将文件中的内容转换成ValueMap类型) 104 * Converts the contents of a file to a ValueMap. 105 * @param filename The filename of the file to gets content. 106 * @return ValueMap of the file contents. 107 * @note This method is used internally. 108 */ 109 virtual ValueMap getValueMapFromFile(const std::string& filename); 110 /** Converts the contents of a file to a ValueMap. 111 * This method is used internally. 112 */ 113 virtual ValueMap getValueMapFromData(const char* filedata, int filesize); 114 /** 写一个内容为ValueMap类型的plist文件 115 * write a ValueMap into a plist file 116 *@param dict the ValueMap want to save 117 *@param fullPath The full path to the file you want to save a string 118 *@return bool 119 */ 120 virtual bool writeToFile(ValueMap& dict, const std::string& fullPath); 121 /** 写一个内容为String类型的.plist文件 122 * write a string into a file 123 * @param dataStr the string want to save 124 * @param fullPath The full path to the file you want to save a string 125 * @return bool True if write success 126 */ 127 virtual bool writeStringToFile(std::string dataStr, const std::string& fullPath); 128 /** 129 * write Data into a file 130 *@param retData the data want to save 131 *@param fullPath The full path to the file you want to save a string 132 *@return bool 133 */ 134 virtual bool writeDataToFile(Data retData, const std::string& fullPath); 135 /** 136 * write ValueMap into a plist file 137 *@param dict the ValueMap want to save 138 *@param fullPath The full path to the file you want to save a string 139 *@return bool 140 */ 141 virtual bool writeValueMapToFile(ValueMap& dict, const std::string& fullPath); 142 /** 143 * write ValueVector into a plist file 144 *@param vecData the ValueVector want to save 145 *@param fullPath The full path to the file you want to save a string 146 *@return bool 147 */ 148 virtual bool writeValueVectorToFile(ValueVector vecData, const std::string& fullPath); 149 /** 150 * Windows fopen can't support UTF-8 filename 151 * Need convert all parameters fopen and other 3rd-party libs 152 * @param filename std::string name file for conversion from utf-8 153 * @return std::string ansi filename in current locale 154 */ 155 virtual std::string getSuitableFOpen(const std::string& filenameUtf8) const; 156 // Converts the contents of a file to a ValueVector. 157 // This method is used internally. 158 virtual ValueVector getValueVectorFromFile(const std::string& filename); 159 /** 判断文件是否存在 160 * Checks whether a file exists. 161 * @note If a relative path was passed in, it will be inserted a default root path at the beginning. 162 * @param filename The path of the file, it could be a relative or absolute path. 163 * @return True if the file exists, false if not. 164 */ 165 virtual bool isFileExist(const std::string& filename) const; 166 /** 获取文件的扩展名是在较低的情况下的后缀(由点从基本文件名隔开)。 167 * Gets filename extension is a suffix (separated from the base filename by a dot) in lower case. 168 * Examples of filename extensions are .png, .jpeg, .exe, .dmg and .txt. 169 * @param filePath The path of the file, it could be a relative or absolute path. 170 * @return suffix for filename in lower case or empty if a dot not found. 171 */ 172 virtual std::string getFileExtension(const std::string& filePath) const; 173 /** 检查路径是否是绝对路径。 174 * Checks whether the path is an absolute path.t. 175 */ 176 virtual bool isAbsolutePath(const std::string& path) const; 177 /**检查路径是否是一个目录。 178 * Checks whether the path is a directory. 179 * @param dirPath The path of the directory, it could be a relative or an absolute path. 180 * @return True if the directory exists, false if not. 181 */ 182 virtual bool isDirectoryExist(const std::string& dirPath) const; 183 /** 创建一个字典目录 184 * Creates a directory. 185 * @param dirPath The path of the directory, it must be an absolute path. 186 * @return True if the directory have been created successfully, false if not. 187 */ 188 virtual bool createDirectory(const std::string& dirPath); 189 /** 移除一个目录 190 * Removes a directory. 191 * @param dirPath The full path of the directory, it must be an absolute path. 192 * @return True if the directory have been removed successfully, false if not. 193 */ 194 virtual bool removeDirectory(const std::string& dirPath); 195 /** 移除一个文件 196 * Removes a file. 197 * @param filepath The full path of the file, it must be an absolute path. 198 * @return True if the file have been removed successfully, false if not. 199 */ 200 virtual bool removeFile(const std::string &filepath); 201 /** 给指定目录下的文件重命名 202 * Renames a file under the given directory. 203 * @param path The parent directory path of the file, it must be an absolute path. 204 * @param oldname The current name of the file. 205 * @param name The new name of the file. 206 * @return True if the file have been renamed successfully, false if not. 207 */ 208 virtual bool renameFile(const std::string &path, const std::string &oldname, const std::string &name); 209 /** 给指定目录下的文件重命名 210 * Renames a file under the given directory. 211 * @param oldfullpath The current fullpath of the file. Includes path and name. 212 * @param newfullpath The new fullpath of the file. Includes path and name. 213 * @return True if the file have been renamed successfully, false if not. 214 */ 215 216 virtual bool renameFile(const std::string &oldfullpath, const std::string &newfullpath); 217 /** 检索文件的大小 218 * Retrieve the file size. 219 * @note If a relative path was passed in, it will be inserted a default root path at the beginning. 220 * @param filepath The path of the file, it could be a relative or absolute path. 221 * @return The file size. 222 */ 223 virtual long getFileSize(const std::string &filepath); 224 /** 返回的完整路径缓存。 225 * Returns the full path cache. 226 */ 227 const std::unordered_map<std::string, std::string>& getFullPathCache() const { return _fullPathCache; } 228 229 protected CONUT: 230 231 /** 在字典中使用一个文件的密钥来查找文件名 232 * Dictionary used to lookup filenames based on a key. 233 * It is used internally by the following methods:基于下面的方法在内部使用 234 * std::string fullPathForFilename(const char*); 235 */ 236 ValueMap _filenameLookupDict; 237 /** 该Vector容器包含有分辨率文件夹。元素在此向量的低指数,该决议目录优先级越高。 238 * The vector contains resolution folders. 239 * The lower index of the element in this vector, the higher priority for this resolution directory. 240 */ 241 std::vector<std::string> _searchResolutionsOrderArray; 242 /**Vector容器包含的搜索路径。 243 * The vector contains search paths. 244 * The lower index of the element in this vector, the higher priority for this search path. 245 */ 246 std::vector<std::string> _searchPathArray; 247 /** 资源的默认根路径。 248 * The default root path of resources. 249 * If the default root path of resources needs to be changed, do it in the `init` method of FileUtils's subclass. 250 * For instance: 251 * On Android, the default root path of resources will be assigned with "assets/" in FileUtilsAndroid::init(). 252 * Similarly on Blackberry, we assign "app/native/Resources/" to this variable in FileUtilsBlackberry::init(). 253 */ 254 std::string _defaultResRootPath; 255 /** 完整路径缓存。当一个文件被发现,它将被添加到该高速缓存。 256 * The full path cache. When a file is found, it will be added into this cache. 257 * This variable is used for improving the performance of file search. 258 */ 259 mutable std::unordered_map<std::string, std::string> _fullPathCache; 260 /**可写路径。 261 * Writable path. 262 */ 263 std::string _writablePath; 264 /** 文件实用的单指针。 265 * The singleton pointer of FileUtils. 266 */ 267 static FileUtils* s_sharedFileUtils;