cocos2d-x  3.3
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
FileUtils Class Referenceabstract

Helper class to handle file operations. More...

#include <CCFileUtils.h>

Inheritance diagram for FileUtils:
CCFileUtilsWinRT FileUtilsAndroid FileUtilsApple FileUtilsLinux FileUtilsWin32

Public Member Functions

virtual ~FileUtils ()
 The destructor of FileUtils. More...
 
virtual void purgeCachedEntries ()
 Purges the file searching cache. More...
 
virtual std::string getStringFromFile (const std::string &filename)
 Gets string from a file. More...
 
virtual Data getDataFromFile (const std::string &filename)
 Creates binary data from a file. More...
 
virtual unsigned char * getFileData (const std::string &filename, const char *mode, ssize_t *size)
 Gets resource file data. More...
 
virtual unsigned char * getFileDataFromZip (const std::string &zipFilePath, const std::string &filename, ssize_t *size)
 Gets resource file data from a zip file. More...
 
virtual std::string fullPathForFilename (const std::string &filename)
 Returns the fullpath for a given filename. More...
 
virtual void loadFilenameLookupDictionaryFromFile (const std::string &filename)
 Loads the filenameLookup dictionary from the contents of a filename. More...
 
virtual void setFilenameLookupDictionary (const ValueMap &filenameLookupDict)
 Sets the filenameLookup dictionary. More...
 
virtual std::string fullPathFromRelativeFile (const std::string &filename, const std::string &relativeFile)
 Gets full path from a file name and the path of the reletive file. More...
 
virtual void setSearchResolutionsOrder (const std::vector< std::string > &searchResolutionsOrder)
 Sets the array that contains the search order of the resources. More...
 
virtual void addSearchResolutionsOrder (const std::string &order, const bool front=false)
 Append search order of the resources. More...
 
virtual const std::vector
< std::string > & 
getSearchResolutionsOrder () const
 Gets the array that contains the search order of the resources. More...
 
virtual void setSearchPaths (const std::vector< std::string > &searchPaths)
 Sets the array of search paths. More...
 
void addSearchPath (const std::string &path, const bool front=false)
 Add search path. More...
 
virtual const std::vector
< std::string > & 
getSearchPaths () const
 Gets the array of search paths. More...
 
virtual std::string getWritablePath () const =0
 Gets the writable path. More...
 
virtual void setPopupNotify (bool notify)
 Sets/Gets whether to pop-up a message box when failed to load an image. More...
 
virtual bool isPopupNotify ()
 
virtual ValueMap getValueMapFromFile (const std::string &filename)
 Converts the contents of a file to a ValueMap. More...
 
virtual ValueMap getValueMapFromData (const char *filedata, int filesize)
 Converts the contents of a file to a ValueMap. More...
 
virtual bool writeToFile (ValueMap &dict, const std::string &fullPath)
 Write a ValueMap to a plist file. More...
 
virtual ValueVector getValueVectorFromFile (const std::string &filename)
 Converts the contents of a file to a ValueVector. More...
 
virtual bool isFileExist (const std::string &filename) const
 Checks whether a file exists. More...
 
virtual bool isAbsolutePath (const std::string &path) const
 Checks whether the path is an absolute path. More...
 
virtual bool isDirectoryExist (const std::string &dirPath)
 Checks whether the path is a directory. More...
 
virtual bool createDirectory (const std::string &dirPath)
 Creates a directory. More...
 
virtual bool removeDirectory (const std::string &dirPath)
 Remove a directory. More...
 
virtual bool removeFile (const std::string &filepath)
 Remove a file. More...
 
virtual bool renameFile (const std::string &path, const std::string &oldname, const std::string &name)
 Rename a file under the given directory. More...
 
virtual long getFileSize (const std::string &filepath)
 Retrieve the file size. More...
 
const std::unordered_map
< std::string, std::string > & 
getFullPathCache () const
 Returns the full path cache. More...
 

Static Public Member Functions

static FileUtilsgetInstance ()
 Gets the instance of FileUtils. More...
 
static void destroyInstance ()
 Destroys the instance of FileUtils. More...
 
static FileUtilssharedFileUtils ()
 
static void purgeFileUtils ()
 

Protected Member Functions

 FileUtils ()
 The default constructor. More...
 
virtual bool init ()
 Initializes the instance of FileUtils. More...
 
virtual std::string getNewFilename (const std::string &filename) const
 Gets the new filename from the filename lookup dictionary. More...
 
virtual bool isFileExistInternal (const std::string &filename) const =0
 Checks whether a file exists without considering search paths and resolution orders. More...
 
virtual bool isDirectoryExistInternal (const std::string &dirPath) const
 Checks whether a directory exists without considering search paths and resolution orders. More...
 
virtual std::string getPathForFilename (const std::string &filename, const std::string &resolutionDirectory, const std::string &searchPath)
 Gets full path for filename, resolution directory and search path. More...
 
virtual std::string getFullPathForDirectoryAndFilename (const std::string &directory, const std::string &filename)
 Gets full path for the directory and the filename. More...
 
virtual std::string searchFullPathForFilename (const std::string &filename) const
 Returns the fullpath for a given filename. More...
 

Protected Attributes

ValueMap _filenameLookupDict
 Dictionary used to lookup filenames based on a key. More...
 
std::vector< std::string > _searchResolutionsOrderArray
 The vector contains resolution folders. More...
 
std::vector< std::string > _searchPathArray
 The vector contains search paths. More...
 
std::string _defaultResRootPath
 The default root path of resources. More...
 
std::unordered_map
< std::string, std::string > 
_fullPathCache
 The full path cache. More...
 

Static Protected Attributes

static FileUtilss_sharedFileUtils
 The singleton pointer of FileUtils. More...
 

Detailed Description

Helper class to handle file operations.

Constructor & Destructor Documentation

virtual ~FileUtils ( )
virtual

The destructor of FileUtils.

NA NA

FileUtils ( )
protected

The default constructor.

Member Function Documentation

void addSearchPath ( const std::string &  path,
const bool  front = false 
)

Add search path.

Since
v2.1
virtual void addSearchResolutionsOrder ( const std::string &  order,
const bool  front = false 
)
virtual

Append search order of the resources.

See also
setSearchResolutionsOrder(), fullPathForFilename().
Since
v2.1
virtual bool createDirectory ( const std::string &  dirPath)
virtual

Creates a directory.

Parameters
dirPathThe path of the directory, it must be an absolute path.
Returns
true if the directory have been created successfully, otherwise it will return false.
static void destroyInstance ( )
static

Destroys the instance of FileUtils.

virtual std::string fullPathForFilename ( const std::string &  filename)
virtual

Returns the fullpath for a given filename.

First it will try to get a new filename from the "filenameLookup" dictionary. If a new filename can't be found on the dictionary, it will use the original filename. Then it will try to obtain the full path of the filename using the FileUtils search rules: resolutions, and search paths. The file search is based on the array element order of search paths and resolution directories.

For instance:

We set two elements("/mnt/sdcard/", "internal_dir/") to search paths vector by setSearchPaths,
and set three elements("resources-ipadhd/", "resources-ipad/", "resources-iphonehd")
to resolutions vector by setSearchResolutionsOrder. The "internal_dir" is relative to "Resources/".

If we have a file named 'sprite.png', the mapping in fileLookup dictionary contains key: sprite.png -> value: sprite.pvr.gz. Firstly, it will replace 'sprite.png' with 'sprite.pvr.gz', then searching the file sprite.pvr.gz as follows:

/mnt/sdcard/resources-ipadhd/sprite.pvr.gz      (if not found, search next)
/mnt/sdcard/resources-ipad/sprite.pvr.gz        (if not found, search next)
/mnt/sdcard/resources-iphonehd/sprite.pvr.gz    (if not found, search next)
/mnt/sdcard/sprite.pvr.gz                       (if not found, search next)
internal_dir/resources-ipadhd/sprite.pvr.gz     (if not found, search next)
internal_dir/resources-ipad/sprite.pvr.gz       (if not found, search next)
internal_dir/resources-iphonehd/sprite.pvr.gz   (if not found, search next)
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.

This method was added to simplify multiplatform support. Whether you are using cocos2d-js or any cross-compilation toolchain like StellaSDK or Apportable, you might need to load different resources for a given file in the different platforms.

Since
v2.1
virtual std::string fullPathFromRelativeFile ( const std::string &  filename,
const std::string &  relativeFile 
)
virtual

Gets full path from a file name and the path of the reletive file.

Parameters
filenameThe file name.
pszRelativeFileThe path of the relative file.
Returns
The full path. 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. )
virtual Data getDataFromFile ( const std::string &  filename)
virtual

Creates binary data from a file.

Returns
A data object.

Reimplemented in FileUtilsAndroid, and FileUtilsWin32.

virtual unsigned char* getFileData ( const std::string &  filename,
const char *  mode,
ssize_t size 
)
virtual

Gets resource file data.

Parameters
[in]filenameThe resource file name which contains the path.
[in]pszModeThe read mode of the file.
[out]pSizeIf the file read operation succeeds, it will be the data size, otherwise 0.
Returns
Upon success, a pointer to the data is returned, otherwise NULL.
Warning
Recall: you are responsible for calling free() on any Non-NULL pointer returned.

Reimplemented in FileUtilsAndroid, and FileUtilsWin32.

virtual unsigned char* getFileDataFromZip ( const std::string &  zipFilePath,
const std::string &  filename,
ssize_t size 
)
virtual

Gets resource file data from a zip file.

Parameters
[in]filenameThe resource file name which contains the relative path of the zip file.
[out]sizeIf the file read operation succeeds, it will be the data size, otherwise 0.
Returns
Upon success, a pointer to the data is returned, otherwise nullptr.
Warning
Recall: you are responsible for calling free() on any Non-nullptr pointer returned.
virtual long getFileSize ( const std::string &  filepath)
virtual

Retrieve the file size.

Note
If a relative path was passed in, it will be inserted a default root path at the beginning.
Parameters
filepathThe path of the file, it could be a relative or absolute path.
Returns
The file size.
const std::unordered_map<std::string, std::string>& getFullPathCache ( ) const
inline

Returns the full path cache.

virtual std::string getFullPathForDirectoryAndFilename ( const std::string &  directory,
const std::string &  filename 
)
protectedvirtual

Gets full path for the directory and the filename.

Note
Only iOS and Mac need to override this method since they are using [[NSBundle mainBundle] pathForResource: ofType: inDirectory:] to make a full path. Other platforms will use the default implementation of this method.
Parameters
strDirectoryThe directory contains the file we are looking for.
strFilenameThe name of the file.
Returns
The full path of the file, if the file can't be found, it will return an empty string.

Reimplemented in FileUtilsWin32, CCFileUtilsWinRT, and FileUtilsApple.

static FileUtils* getInstance ( )
static

Gets the instance of FileUtils.

virtual std::string getNewFilename ( const std::string &  filename) const
protectedvirtual

Gets the new filename from the filename lookup dictionary.

It is possible to have a override names.

Parameters
filenameThe original filename.
Returns
The new filename after searching in the filename lookup dictionary. If the original filename wasn't in the dictionary, it will return the original filename.

Reimplemented in FileUtilsAndroid.

virtual std::string getPathForFilename ( const std::string &  filename,
const std::string &  resolutionDirectory,
const std::string &  searchPath 
)
protectedvirtual

Gets full path for filename, resolution directory and search path.

Parameters
filenameThe file name.
resolutionDirectoryThe resolution directory.
searchPathThe search path.
Returns
The full path of the file. It will return an empty string if the full path of the file doesn't exist.

Reimplemented in FileUtilsWin32, and CCFileUtilsWinRT.

virtual const std::vector<std::string>& getSearchPaths ( ) const
virtual

Gets the array of search paths.

Returns
The array of search paths.
See also
fullPathForFilename(const char*). NA
virtual const std::vector<std::string>& getSearchResolutionsOrder ( ) const
virtual

Gets the array that contains the search order of the resources.

See also
setSearchResolutionsOrder(const std::vector<std::string>&), fullPathForFilename(const char*).
Since
v2.1 NA
virtual std::string getStringFromFile ( const std::string &  filename)
virtual

Gets string from a file.

Reimplemented in FileUtilsAndroid, FileUtilsWin32, and CCFileUtilsWinRT.

virtual ValueMap getValueMapFromData ( const char *  filedata,
int  filesize 
)
virtual

Converts the contents of a file to a ValueMap.

Note
This method is used internally.

Reimplemented in FileUtilsApple.

virtual ValueMap getValueMapFromFile ( const std::string &  filename)
virtual

Converts the contents of a file to a ValueMap.

Note
This method is used internally.

Reimplemented in FileUtilsApple.

virtual ValueVector getValueVectorFromFile ( const std::string &  filename)
virtual

Converts the contents of a file to a ValueVector.

Note
This method is used internally.

Reimplemented in FileUtilsApple.

virtual std::string getWritablePath ( ) const
pure virtual

Gets the writable path.

Returns
The path that can be write/read a file in

Implemented in FileUtilsAndroid, FileUtilsLinux, FileUtilsWin32, CCFileUtilsWinRT, and FileUtilsApple.

virtual bool init ( )
protectedvirtual

Initializes the instance of FileUtils.

It will set _searchPathArray and _searchResolutionsOrderArray to default values.

Note
When you are porting Cocos2d-x to a new platform, you may need to take care of this method. You could assign a default value to _defaultResRootPath in the subclass of FileUtils(e.g. FileUtilsAndroid). Then invoke the FileUtils::init().
Returns
true if successed, otherwise it returns false.

Reimplemented in FileUtilsAndroid, FileUtilsLinux, FileUtilsWin32, and CCFileUtilsWinRT.

virtual bool isAbsolutePath ( const std::string &  path) const
virtual

Checks whether the path is an absolute path.

Note
On Android, if the parameter passed in is relative to "assets/", this method will treat it as an absolute path. Also on Blackberry, path starts with "app/native/Resources/" is treated as an absolute path.
Parameters
strPathThe path that needs to be checked.
Returns
true if it's an absolute path, otherwise it will return false.

Reimplemented in FileUtilsAndroid, FileUtilsWin32, and CCFileUtilsWinRT.

virtual bool isDirectoryExist ( const std::string &  dirPath)
virtual

Checks whether the path is a directory.

Parameters
dirPathThe path of the directory, it could be a relative or an absolute path.
Returns
true if the directory exists, otherwise it will return false.
virtual bool isDirectoryExistInternal ( const std::string &  dirPath) const
protectedvirtual

Checks whether a directory exists without considering search paths and resolution orders.

Parameters
Thedirectory (with absolute path) to look up for
Returns
Returns true if the directory found at the given absolute path, otherwise returns false
virtual bool isFileExist ( const std::string &  filename) const
virtual

Checks whether a file exists.

Note
If a relative path was passed in, it will be inserted a default root path at the beginning.
Parameters
strFilePathThe path of the file, it could be a relative or absolute path.
Returns
true if the file exists, otherwise it will return false.
virtual bool isFileExistInternal ( const std::string &  filename) const
protectedpure virtual

Checks whether a file exists without considering search paths and resolution orders.

Parameters
Thefile (with absolute path) to look up for
Returns
Returns true if the file found at the given absolute path, otherwise returns false

Implemented in FileUtilsWin32.

virtual bool isPopupNotify ( )
virtual
virtual void loadFilenameLookupDictionaryFromFile ( const std::string &  filename)
virtual

Loads the filenameLookup dictionary from the contents of a filename.

Note
The plist file name should follow the format below:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>filenames</key>
<dict>
<key>sounds/click.wav</key>
<string>sounds/click.caf</string>
<key>sounds/endgame.wav</key>
<string>sounds/endgame.caf</string>
<key>sounds/gem-0.wav</key>
<string>sounds/gem-0.caf</string>
</dict>
<key>metadata</key>
<dict>
<key>version</key>
<integer>1</integer>
</dict>
</dict>
</plist>
Parameters
filenameThe plist file name.
Since
v2.1 loadFilenameLookup loadFilenameLookup
virtual void purgeCachedEntries ( )
virtual

Purges the file searching cache.

Note
It should be invoked after the resources were updated. For instance, in the CocosPlayer sample, every time you run application from CocosBuilder, All the resources will be downloaded to the writable folder, before new js app launchs, this method should be invoked to clean the file search cache.
static void purgeFileUtils ( )
inlinestatic
virtual bool removeDirectory ( const std::string &  dirPath)
virtual

Remove a directory.

Parameters
dirPathThe full path of the directory, it must be an absolute path.
Returns
true if the directory have been removed successfully, otherwise it will return false.
virtual bool removeFile ( const std::string &  filepath)
virtual

Remove a file.

Parameters
filepathThe full path of the file, it must be an absolute path.
Returns
true if the file have been removed successfully, otherwise it will return false.
virtual bool renameFile ( const std::string &  path,
const std::string &  oldname,
const std::string &  name 
)
virtual

Rename a file under the given directory.

Parameters
pathThe parent directory path of the file, it must be an absolute path.
oldnameThe current name of the file.
nameThe new name of the file.
Returns
true if the file have been renamed successfully, otherwise it will return false.
virtual std::string searchFullPathForFilename ( const std::string &  filename) const
protectedvirtual

Returns the fullpath for a given filename.

This is an alternative for fullPathForFilename, there are two main differences: First, it returns empty string instead of the original filename when no file found for the given name. Secondly, it's a const function.

Parameters
filenameThe file name to look up for
Returns
The full path for the file, if not found, the return value will be an empty string
virtual void setFilenameLookupDictionary ( const ValueMap filenameLookupDict)
virtual

Sets the filenameLookup dictionary.

Parameters
pFilenameLookupDictThe dictionary for replacing filename.
Since
v2.1
virtual void setPopupNotify ( bool  notify)
virtual

Sets/Gets whether to pop-up a message box when failed to load an image.

virtual void setSearchPaths ( const std::vector< std::string > &  searchPaths)
virtual

Sets the array of search paths.

You can use this array to modify the search path of the resources. If you want to use "themes" or search resources in the "cache", you can do it easily by adding new entries in this array.

Note
This method could access relative path and absolute path. If the relative path was passed to the vector, FileUtils will add the default resource directory before the relative path. For instance: On Android, the default resource root path is "assets/". If "/mnt/sdcard/" and "resources-large" were set to the search paths vector, "resources-large" will be converted to "assets/resources-large" since it was a relative path.
Parameters
searchPathsThe array contains search paths.
See also
fullPathForFilename(const char*)
Since
v2.1 In js:var setSearchPaths(var jsval); NA
virtual void setSearchResolutionsOrder ( const std::vector< std::string > &  searchResolutionsOrder)
virtual

Sets the array that contains the search order of the resources.

Parameters
searchResolutionsOrderThe source array that contains the search order of the resources.
See also
getSearchResolutionsOrder(void), fullPathForFilename(const char*).
Since
v2.1 In js:var setSearchResolutionsOrder(var jsval) NA
static FileUtils* sharedFileUtils ( )
inlinestatic
virtual bool writeToFile ( ValueMap dict,
const std::string &  fullPath 
)
virtual

Write a ValueMap to a plist file.

Note
This method is used internally.

Reimplemented in FileUtilsApple.

Member Data Documentation

std::string _defaultResRootPath
protected

The default root path of resources.

If the default root path of resources needs to be changed, do it in the init method of FileUtils's subclass. For instance: On Android, the default root path of resources will be assigned with "assets/" in FileUtilsAndroid::init(). Similarly on Blackberry, we assign "app/native/Resources/" to this variable in FileUtilsBlackberry::init().

ValueMap _filenameLookupDict
protected

Dictionary used to lookup filenames based on a key.

It is used internally by the following methods:

std::string fullPathForFilename(const char*);

Since
v2.1
std::unordered_map<std::string, std::string> _fullPathCache
protected

The full path cache.

When a file is found, it will be added into this cache. This variable is used for improving the performance of file search.

std::vector<std::string> _searchPathArray
protected

The vector contains search paths.

The lower index of the element in this vector, the higher priority for this search path.

std::vector<std::string> _searchResolutionsOrderArray
protected

The vector contains resolution folders.

The lower index of the element in this vector, the higher priority for this resolution directory.

FileUtils* s_sharedFileUtils
staticprotected

The singleton pointer of FileUtils.


The documentation for this class was generated from the following file: