The Filesystem API provides access to a device's filesystem.
The filesystem is represented as an abstract collection of disjointed filesystem virtual root locations, each corresponding to a specific location in the device filesystem. The filesystem API exposes the hierarchies below these root locations as autonomous virtual filesystems.
Each virtual root has a string name. Each file or directory within the virtual filesystem is addressed using a fully-qualified path of the form: <root name>/<path> where <rootname> is the name of the virtual root and <path> is the path to the file or directory relative to that root.
The following virtual roots must be supported:
images - the location for images
videos - the location for videos
music - the location for sounds
documents - the location for documents
downloads - the location for downloaded items
camera - the location for the pictures and videos taken by a device (supported since Tizen 2.3)
wgt-package - the location for widget package which is read-only
wgt-private - the location for a widget's private storage
wgt-private-tmp - the location for a widget's private volatile storage
removable_... - the location for external storages. The "..." suffix is a unique identifier of an external storage. To obtain list of available external storages use listStorages.
The file URI path is also supported. To access paths out of virtual root, for example "file:///tmp" can be used as location parameter.
The implementation must support the use of the following characters in file names:
Letters (a-z, A-Z)
Digits (0-9)
Blank space
Underscore ("_")
Hyphen ("-")
Period (".")
The implementation may support additional characters in file names, depending on platform support.
The implementation may forbid the use of additional characters in file names, depending on the platform. The use of the path (component) separator "/" and null character "x00" should not be allowed in file names.
Some other file name and path characteristics are platform-dependent, for example, maximum path length, file name length, case sensitivity, additional character support, etc. Therefore, it is recommended to avoid any dependency on aspects that cannot be supported across multiple platforms.
The encoding used for the file path should be UTF-16 (default for ECMAScript String).
Remark: In order to access files, a proper privilege has to be defined additionally:
Remark: Methods, which names end with NonBlocking are asynchronous and are executed in background in the order in which they were called. Corresponding methods without NonBlocking at the end are synchronous and will block further instructions execution, until they are finished.
For more information on the Filesystem features, see File System Guide.
This manager interface exposes the Filesystem base API and provides functionalities, such as determining root and default locations, resolving a given location into a file handle and registering filesystem listeners for filesystem events.
Attributes
readonly long maxNameLength
The maximum file or directory name length for the current platform.
Since: 5.0
Code example:
console.log("The maximum name length is " + tizen.filesystem.maxNameLength);
Output example:
The maximum name length is 255
readonly long maxPathLength
The maximum path length limit for the current platform.
Since: 1.0
Code example:
console.log("The maximum path length is " + tizen.filesystem.maxPathLength);
If the operation succeeds, a file handle to the newly created or opened file is returned, otherwise an exception is thrown.
Following file open modes are supported:
a - append mode. File position indicator is always set to the first position after the last character of the file and cannot be modified with seek operations. Write operations always append content to the end of the file. Original file content are not modified. Read operations cannot be performed. If the file does not exist, it is created.
r - read mode. File position indicator is initially set to the beginning of the file and may be changed with seek operations. Write operations cannot be performed. Original file content may be read in this mode. If the file does not exist, NotFoundError is thrown.
rw - read and write mode. File position indicator is initially set to the beginning of the file and may be changed with seek operations. Original file content may be read or modified in this mode. If the file does not exist, NotFoundError will be thrown.
rwo - read and write mode, overwriting existing file content. File position indicator is initially set to the beginning of the file. Read and write operations may be performed. Original file content are deleted before opening the file. If the file does not exist, it is created.
w - write mode. File position indicator is initially set to the beginning of the file and may be changed with seek operations. Read operations cannot be performed. Original file content are deleted before opening the file. If the file does not exist, it is created.
Remark: Write permission is needed, when file is opened in modes: a, rw, rwo and w. Read permission is needed, when file is opened in modes: r, rw and rwo.
Parameters:
path: Path to the file.
openMode: Mode in which the file is to be opened.
makeParents[optional]: Flag indicating whether lacking directories should be created. For instance, if method is invoked with parameter path equal to documents/path/to/dir/file.ext and there is no directory "path" in "documents" virtual root, directories "path", "to" and "dir" will be created, as well as the new file "file.ext". By default, makeParents is equal to true. Its value is ignored, when openMode is r or rw.
Return value:
FileHandle: Object representing open file.
Exceptions:
WebAPIException
with error type IOError, if a file is not available for open or any other IO error occurs.
with error type NotFoundError, if the path does not point to an existing file.
with error type SecurityError, if the application does not have the privilege to call this method or the application does not have privilege to access the storage. For more information, see Storage privileges.
with error type TypeMismatchError, if any of the input parameters is not compatible with the expected type for that parameter.
Code example:
/* Opening file for write - file is created if not exists, */
/* otherwise existing file is truncated. */
var fileHandleWrite = tizen.filesystem.openFile("documents/file", "w");
console.log("File opened for writing");
fileHandleWrite.writeString("Lorem ipsum dolor sit amet...");
console.log("String has been written to the file");
fileHandleWrite.close();
/* Opening file for read - this code assumes that there is */
/* a file named "file" in documents directory. */
var fileHandleRead = tizen.filesystem.openFile("documents/file", "r");
console.log("File opened for reading");
var fileContent = fileHandleRead.readString();
console.log("File content: " + fileContent);
fileHandleRead.close();
Output example:
File opened for writing
String has been written to the file
File opened for reading
File content: Lorem ipsum dolor sit amet...
makeParents[optional]: Flag indicating whether lacking directories should be created. For instance, if method is invoked with parameter path equal to documents/path/to/dir and there is no directory "path" in "documents" virtual root, directories "path", "to" and "dir" will be created. By default, makeParents is equal to true.
successCallback[optional][nullable]: Callback function to be invoked on success.
errorCallback[optional][nullable]: Callback function to be invoked when an error occurs.
Exceptions:
WebAPIException
with error type InvalidValuesError, if the path is invalid.
with error type SecurityError, if the application does not have the privilege to call this method or the application does not have privilege to access the storage. For more information, see Storage privileges.
with error type TypeMismatchError, if any of the input parameters is not compatible with the expected type for that parameter.
Code example:
function errorCallback(error)
{
console.log("An error occurred, during directory creation: " + error.message);
}
function successCallback(path)
{
console.log("The directory has been created, path to created directory: " + path);
/* Directory can now be accessed. */
}
try
{
tizen.filesystem.createDirectory(
"documents/foo_dir/bar_dir", true, successCallback, errorCallback);
}
catch (error)
{
console.log("Directory cannot be created: " + error.message);
}
Output example:
The directory has been created, path to created directory: documents/foo_dir/bar_dir
successCallback[optional][nullable]: Callback function to be invoked on success.
errorCallback[optional][nullable]: Callback function to be invoked when an error occurs.
Exceptions:
WebAPIException
with error type InvalidValuesError, if the path is invalid.
with error type SecurityError, if the application does not have the privilege to call this method or the application does not have privilege to access the storage. For more information, see Storage privileges.
with error type TypeMismatchError, if any of the input parameters is not compatible with the expected type for that parameter.
Code example:
function errorCallback(error)
{
console.log("An error occurred, during file deletion: " + error.message);
}
function successCallback(path)
{
console.log("The file has been deleted, path to the parent of deleted file: " + path);
}
try
{
tizen.filesystem.deleteFile("documents/foo", successCallback, errorCallback);
}
catch (error)
{
console.log("File cannot be deleted: " + error.message);
}
Output example:
The file has been deleted, path to the parent of deleted file: documents
deleteDirectory
Deletes directory or directory tree under the current directory pointed by path.
recursive[optional]: Flag indicating whether the deletion is recursive or not. If recursive is set to true the method will delete content of a given directory recursively. Otherwise, the method succeeds only if the directory is empty, on other cases errorCallback is called. By default, recursive is equal to true.
successCallback[optional][nullable]: Callback function to be invoked on success.
errorCallback[optional][nullable]: Callback function to be invoked when an error occurs.
Exceptions:
WebAPIException
with error type InvalidValuesError, if the path is invalid.
with error type SecurityError, if the application does not have the privilege to call this method or the application does not have privilege to access the storage. For more information, see Storage privileges.
with error type TypeMismatchError, if any of the input parameters is not compatible with the expected type for that parameter.
Code example:
function errorCallback(error)
{
console.log("An error occurred, during directory deletion: " + error.message);
}
function successCallback(path)
{
console.log("The directory has been deleted, path to the parent of deleted directory: " + path);
}
try
{
tizen.filesystem.deleteDirectory("documents/foo_dir", true, successCallback, errorCallback);
}
catch (error)
{
console.log("Directory cannot be deleted: " + error.message);
}
Output example:
The directory has been deleted, path to the parent of deleted directory: documents
copyFile
Copies file from location pointed by sourcePath to destinationPath.
destinationPath: Path for copied file. The path must consist of path to an existing directory concatenated with '/' and the name of new file.
overwrite[optional]: Flag indicating whether to overwrite an existing file. If overwrite is set to true and file pointed by destinationPath already exists, the method will overwrite the file. Otherwise, if a file with conflicting name already exists errorCallback is called. By default, overwrite is equal to false.
successCallback[optional][nullable]: Callback function to be invoked on success.
errorCallback[optional][nullable]: Callback function to be invoked when an error occurs.
Exceptions:
WebAPIException
with error type InvalidValuesError, if any of the input parameters contains an invalid value. For example, the sourcePath or the destinationPath is invalid.
with error type SecurityError, if the application does not have the privilege to call this method or the application does not have privilege to access the storage. For more information, see Storage privileges.
with error type TypeMismatchError, if any of the input parameters is not compatible with the expected type for that parameter.
Code example:
function errorCallback(error)
{
console.log("An error occurred, during copy operation: " + error.message);
}
function successCallback(path)
{
console.log("The file has been copied, path to copied file: " + path);
/* File copy can now be accessed. */
}
try
{
tizen.filesystem.copyFile("documents/foo", "documents/bar", true, successCallback, errorCallback);
}
catch (error)
{
console.log("Copy operation cannot be performed: " + error.message);
}
Output example:
The file has been copied, path to copied file: documents/bar
copyDirectory
Recursively copies directory pointed by sourcePath to destinationPath.
The method merges content of the directory pointed by sourcePath with content of the directory pointed by destinationPath, if exists. If the directory pointed by destinationPath does not exist, it is created.
Successful directory copying invokes successCallback function, if specified. In case of failure errorCallback function is invoked, if specified.
The ErrorCallback is launched with these error types:
IOError, if a directory with conflicting name already exists and overwrite is equal to false or any of the input/output error occurs.
NotFoundError, if the sourcePath does not point to an existing directory.
destinationPath: Path for copied directory. The path must consist of path to an existing directory concatenated with '/' and the name of destination directory.
overwrite[optional]: Flag indicating whether to overwrite existing content. If overwrite is equal to true, the file or directory with conflicting name will be overwritten. Otherwise, errorCallback will be called with IOError. By default, overwrite is equal to false.
successCallback[optional][nullable]: Callback function to be invoked on success.
errorCallback[optional][nullable]: Callback function to be invoked when an error occurs.
Exceptions:
WebAPIException
with error type InvalidValuesError, if any of the input parameters contains an invalid value. For example, the sourcePath or the destinationPath is invalid.
with error type SecurityError, if the application does not have the privilege to call this method or the application does not have privilege to access the storage. For more information, see Storage privileges.
with error type TypeMismatchError, if any of the input parameters is not compatible with the expected type for that parameter.
Code example:
function errorCallback(error)
{
console.log("An error occurred, during copy operation: " + error.message);
}
function successCallback(path)
{
console.log("The directory has been copied, path to copied directory: " + path);
/* Directory copy can now be accessed. */
}
try
{
tizen.filesystem.copyDirectory(
"documents/foo_dir", "documents/bar_dir", true, successCallback, errorCallback);
}
catch (error)
{
console.log("Copy operation cannot be performed: " + error.message);
}
Output example:
The directory has been copied, path to copied directory: documents/bar_dir
Code example:
function errorCallback(error)
{
console.log("An error occurred: " + error.message);
}
function createFooDirCallback()
{
tizen.filesystem.createDirectory(
"documents/foo_dir/dir_2", true, createFileCallback, errorCallback);
}
function listCallback(files, path)
{
console.log("Found inside " + path + " directory:");
for (var i = 0; i < files.length; i++)
{
console.log(files[i]);
}
}
function successCallback(path)
{
console.log("The directory has been created and copied, path to directory: " + path);
/* Directory 'documents/bar_dir' content is as below: */
/* documents/bar_dir/dir_1 */
/* documents/bar_dir/dir_2 */
/* documents/bar_dir/dir_1/file */
tizen.filesystem.listDirectory("documents/bar_dir", listCallback, errorCallback);
tizen.filesystem.listDirectory("documents/bar_dir/dir_1", listCallback, errorCallback);
}
function createFileCallback()
{
tizen.filesystem.openFile("documents/foo_dir/dir_1/file", "w").close();
try
{
tizen.filesystem.copyDirectory(
"documents/foo_dir", "documents/bar_dir", true, successCallback, errorCallback);
}
catch (error)
{
console.log("Copy operation cannot be performed: " + error.message);
}
}
tizen.filesystem.createDirectory(
"documents/foo_dir/dir_1", true, createFooDirCallback, errorCallback);
Output example:
The directory has been created and copied, path to directory: documents/bar_dir
Found inside documents/bar_dir directory:
dir_1
dir_2
Found inside documents/bar_dir/dir_1 directory:
file
moveFile
Moves file pointed by sourcePath to destinationPath.
destinationPath: A destination directory path to move the file to.
overwrite[optional]: Flag indicating whether to overwrite an existing file. If overwrite is set to true and file with the same name in destinationPath already exists, the method will overwrite the file. Otherwise, if a file with conflicting name already exists errorCallback is called. By default, overwrite is equal to false.
successCallback[optional][nullable]: Callback function to be invoked on success.
errorCallback[optional][nullable]: Callback function to be invoked when an error occurs.
Exceptions:
WebAPIException
with error type InvalidValuesError, if any of the input parameters contains an invalid value. For example, the sourcePath or the destinationPath is invalid.
with error type SecurityError, if the application does not have the privilege to call this method or the application does not have privilege to access the storage. For more information, see Storage privileges.
with error type TypeMismatchError, if any of the input parameters is not compatible with the expected type for that parameter.
Code example:
function errorCallback(error)
{
console.log("An error occurred, during move operation: " + error.message);
}
function successCallback(path)
{
console.log("The file has been moved, path to moved file: " + path);
/* Moved file can now be accessed. */
}
try
{
tizen.filesystem.moveFile(
"documents/foo", "documents/foo_dir/", false, successCallback, errorCallback);
}
catch (error)
{
console.log("Move operation cannot be performed: " + error.message);
}
Output example:
The file has been moved, path to moved file: documents/foo_dir/foo
moveDirectory
Recursively moves directory pointed by sourcePath to destinationPath.
destinationPath: A destination directory path to move the directory to.
overwrite[optional]: Flag indicating whether to overwrite existing content. If overwrite is equal to true, the file or directory with conflicting name will be overwritten. Otherwise, errorCallback will be called with IOError. By default, overwrite is equal to false.
successCallback[optional][nullable]: Callback function to be invoked on success.
errorCallback[optional][nullable]: Callback function to be invoked when an error occurs.
Exceptions:
WebAPIException
with error type InvalidValuesError, if any of the input parameters contains an invalid value. For example, the sourcePath or the destinationPath is invalid.
with error type SecurityError, if the application does not have the privilege to call this method or the application does not have privilege to access the storage. For more information, see Storage privileges.
with error type TypeMismatchError, if any of the input parameters is not compatible with the expected type for that parameter.
Code example:
function errorCallback(error)
{
console.log("An error occurred, during move operation: " + error.message);
}
function successCallback(path)
{
console.log("The directory has been moved, path to moved directory: " + path);
/* Moved directory can now be accessed. */
}
try
{
tizen.filesystem.moveDirectory(
"documents/foo_dir", "documents/bar_dir/", false, successCallback, errorCallback);
}
catch (error)
{
console.log("Move operation cannot be performed: " + error.message);
}
Output example:
The directory has been moved, path to moved directory: documents/bar_dir/foo_dir
rename
Renames file or directory located in path to name newName.
successCallback[optional][nullable]: Callback function to be invoked on success.
errorCallback[optional][nullable]: Callback function to be invoked when an error occurs.
Exceptions:
WebAPIException
with error type InvalidValuesError, if the path or newName is invalid.
with error type SecurityError, if the application does not have the privilege to call this method or the application does not have privilege to access the storage. For more information, see Storage privileges.
with error type TypeMismatchError, if any of the input parameters is not compatible with the expected type for that parameter.
Code example:
function errorCallback(error)
{
console.log("An error occurred, during rename operation: " + error.message);
}
function successCallback(path)
{
console.log("The file has been renamed, path to renamed file or directory: " + path);
}
try
{
tizen.filesystem.rename("documents/foo", "bar", successCallback, errorCallback);
}
catch (error)
{
console.log("Rename operation cannot be performed: " + error.message);
}
Output example:
The file has been renamed, path to renamed file or directory: documents/bar
Successful listing of directory content invokes successCallback function, if specified. In case of failure errorCallback function is invoked, if specified.
If the filter is passed and contains valid values, only those directories or files in the directory that match the filter criteria specified in the FileFilter interface are returned in successCallback method. If the filter is null or undefined the implementation must return the full list of files in the directory.
If the directory does not contain any files or directories, or the filter criteria do not match with any files or directories, the successCallback is invoked with an empty array.
The ErrorCallback is launched with these error types:
IOError, if any of the input/output error occurs.
NotFoundError, if the path does not point to an existing directory.
successCallback: Callback function to be invoked on success.
errorCallback[optional][nullable]: Callback function to be invoked when an error occurs.
filter[optional][nullable]: Filter to restrict the listed files.
Exceptions:
WebAPIException
with error type InvalidValuesError, if any of the input parameters contains an invalid value. For example, the path is invalid.
with error type SecurityError, if the application does not have the privilege to call this method or the application does not have privilege to access the storage. For more information, see Storage privileges.
with error type TypeMismatchError, if any of the input parameters is not compatible with the expected type for that parameter.
Code example:
function errorCallback(error)
{
console.log("An error occurred, during directory listing: " + error.message);
}
function successCallback(files, path)
{
console.log("Found directories in " + path + " directory:");
for (var i = 0; i < files.length; i++)
{
console.log(files[i]);
}
}
try
{
var start = new Date("Jan 01 2018 00:00:00");
tizen.filesystem.listDirectory("documents/", successCallback, errorCallback,
{name: "foo_%", isDirectory: true, startModified: start});
}
catch (error)
{
console.log("Directory listing cannot be performed: " + error.message);
}
Output example:
Found directories in documents/ directory:
foo_dir_c
foo_dir_b
foo_dir_d
foo_dir_a
toURI
Converts path to file URI.
DOMString toURI(Path path);
Since: 5.0
Remark: The function does not check if path exists in filesystem.
with error type InvalidValuesError, if the path is invalid.
Code example:
var path1 = tizen.filesystem.toURI("documents/directory/file.ext");
var path2 = tizen.filesystem.toURI("/opt/usr/home/owner/content/Documents/directory/file.ext");
var path3 =
tizen.filesystem.toURI("file:///opt/usr/home/owner/content/Documents/directory/file.ext");
/* All above paths point to the same file. */
console.log(path1);
console.log(path2);
console.log(path3);
var mmcPath = tizen.filesystem.toURI("removable_sda1/Documents/directory/file");
console.log(mmcPath);
boolean: true if path points to a file, false otherwise.
Exceptions:
WebAPIException
with error type InvalidValuesError, if the path is invalid.
with error type IOError, if any of the input/output error occurs.
with error type NotFoundError, if the path does not point to an existing file or directory.
with error type SecurityError, if the application does not have the privilege to call this method or the application does not have privilege to access the storage. For more information, see Storage privileges.
Code example:
console.log("documents/foo_file is " +
(tizen.filesystem.isFile("documents/foo_file") ? "file" : "directory"));
boolean: true if path points to a directory, false otherwise.
Exceptions:
WebAPIException
with error type InvalidValuesError, if the path is invalid.
with error type IOError, if any of the input/output error occurs.
with error type NotFoundError, if the path does not point to an existing file or directory.
with error type SecurityError, if the application does not have the privilege to call this method or the application does not have privilege to access the storage. For more information, see Storage privileges.
Code example:
console.log("documents/foo_dir is " +
(tizen.filesystem.isDirectory("documents/foo_dir") ? "directory" : "file"));
boolean: true if path points to a existing element, false otherwise.
Exceptions:
WebAPIException
with error type InvalidValuesError, if the path is invalid.
with error type IOError, if input/output error occurs.
with error type SecurityError, if the application does not have the privilege to call this method or the application does not have privilege to access the storage. For more information, see Storage privileges.
Code example:
console.log("documents/foo " +
(tizen.filesystem.pathExists("documents/foo") ? "exists" : "does not exist"));
Output example:
documents/foo does not exist
getDirName
Returns path to directory for given path.
DOMString getDirName(DOMString path);
Since: 5.0
Strips trailing '/', then breaks path into two components by last path separator, returns first component.
Remark: This function does not check if path is valid or exists in filesystem.
A location can contain a virtual path like "documents/some_file.txt" or a file URI like "file:///my_strange_path/some_file.png". A location is not allowed to contain the "." or ".." directory entries inside its value.
The list of root locations that must be supported by a compliant implementation are:
documents - The default folder in which text documents (such as pdf, doc...) are stored by default in a device. For example, in some platforms it corresponds to the "My Documents" folder.
images - The default folder in which still images, like pictures (in formats including jpg, gif, png, etc.), are stored in the device by default. For example, in some platforms it corresponds to the "My Images" folder.
music - The default folder in which sound clips (in formats including mp3, aac, etc.) are stored in the device by default. For example, in some platforms it corresponds to the "My Music" folder.
videos - The default folder in which video clips (in formats including avi, mp4, etc.) are stored in the device by default. For example, in some platforms it corresponds to the "My Videos" folder.
downloads - The default folder in which downloaded files (from sources including browser, e-mail client, etc.) are stored by default in the device. For example, in some platforms it corresponds to the "Downloads" folder.
ringtones - The default folder in which ringtones (such as mp3, etc.) are stored in the device.
camera - The default folder in which pictures and videos taken by a device are stored.
wgt-package - The read-only folder to which the content of a widget file is extracted.
wgt-private - The private folder in which a widget stores its information. This folder must be accessible only to the same widget and other widgets or applications must not be able to access the stored information.
wgt-private-tmp - Temporary, the private folder in which a widget can store data that is available during a widget execution cycle. Content of this folder can be removed from this directory when the widget is closed or the Web Runtime is restarted. This folder must be accessible only to the same widget and other widgets or applications must not be able to access it.
The mode parameter specifies whether the resulting File object has read-only access (r access), read and write access (rw access), append access (a access), or write access (w access) to the root location containing directory tree. Permission for the requested access is obtained from the security framework. Once the resulting File object has access, access is inherited by any other File objects that are derived from this instance without any further reference to the security framework, as noted in descriptions of certain methods of File.
The ErrorCallback is launched with these error types:
InvalidValuesError - If any of the input parameters contains an invalid value. For example, the mode is w for the read-only virtual roots (wgt-package and ringtones).
NotFoundError - If the location input argument does not correspond to a valid location.
Remark: camera location is supported since Tizen 2.3. If a device does not support camera, NotSupportedError will be thrown.
Parameters:
location: Location to resolve that can be a virtual path or file URI.
onsuccess: Callback method to be invoked when the location has been successfully resolved, passing the newly created File object.
onerror[optional][nullable]: Callback method to be invoked when an error has occurred.
mode[optional][nullable]: Optional value to indicate the file access mode on all files and directories that can be reached from the File object passed to onsuccess.
Default value of this parameter is rw if absent or null.
Exceptions:
WebAPIException
with error type NotSupportedError, if this feature is not supported (e.g. in the case of "camera" virtual path if the device does not support camera), or if mode has been set to "rwo", which was introduced in tizen version 5.0
with error type SecurityError, if the application does not have the privilege to call this method or the application does not have privilege to access the storage. For more information, see Storage privileges.
with error type TypeMismatchError, if any of the input parameters is not compatible with the expected type for that parameter.
Code example:
tizen.filesystem.resolve("images",
function(dir)
{
console.log("Images are stored in " + dir.path);
},
function(e)
{
console.log("Error: " + e.message);
},
"r");
getStorage
Gets information about a storage based on its label.
For example: "MyThumbDrive", "InternalFlash".
onsuccess: Callback method to be invoked when the list of storages is available, passing the storage list to the callback.
onerror[optional][nullable]: Callback method to be invoked when an error occurs.
Exceptions:
WebAPIException
with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.
with error type SecurityError, if the application does not have the privilege to call this method. For more information, see Storage privileges.
Code example:
function onStorage(storage)
{
/* Do something. */
}
function onStorageError(e)
{
console.log("Storage not found: " + e.message);
}
tizen.filesystem.getStorage("music", onStorage, onStorageError);
listStorages
Lists the available storages (both internal and external) on a device. The onsuccess method receives a list of the data structures as input argument containing additional information about each drive found. It can get storages that would have a label named as "internal0", virtual roots (images, documents, ...), "removable1", "removable2". "removable1" label is used to resolve sdcard and "removable2" label is used to resolve USB host, if supported. The vfat filesystem used to sdcard filesystem widely is not case-sensitive. If you want to handle the file on sdcard, you need to consider
case-sensitive filenames are regarded as same name.
onsuccess: Callback method to be invoked when a list of storage is available and passing the storage list to the callback.
onerror[optional][nullable]: Callback method to be invoked when an error occurs.
Exceptions:
WebAPIException
with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.
with error type SecurityError, if the application does not have the privilege to call this method. For more information, see Storage privileges.
Code example:
function alertForCorruptedRemovableDrives(storages)
{
for (var i = 0; i < storages.length; i++)
{
if (storages[i].type != "EXTERNAL")
continue;
if (storages[i].state == "UNMOUNTABLE")
console.log("External drive " + storages[i].label + " is corrupted.");
}
}
tizen.filesystem.listStorages(alertForCorruptedRemovableDrives);
addStorageStateChangeListener
Adds a listener to subscribe to notifications when a change in storage state occurs.
long addStorageStateChangeListener(FileSystemStorageSuccessCallback onsuccess, optional ErrorCallback? onerror);
Since: 1.0
The most common usage for this method is to watch for any additions and removals of external storages.
When executed, it returns a subscription identifier that identifies the watch operation. After returning the identifier, the watch operation is started asynchronously. The onsuccess method will be invoked every time a storage state changes. If the attempt fails, the onerror if present will be invoked with the relevant error type.
The watch operation must continue until the removeStorageStateChangeListener() method is called with the corresponding subscription identifier.
If the watchId argument is valid and corresponds to a subscription already in place, the watch process will be stopped and no further callbacks will be invoked. Otherwise, the method call has no effect.
with error type SecurityError, if the application does not have the privilege to call this method. For more information, see Storage privileges.
with error type UnknownError, if any other error occurs.
Code example:
var watchID;
function onStorageStateChanged(storage)
{
if (storage.state == "MOUNTED") console.log("Storage " + storage.label + " was added!");
tizen.filesystem.removeStorageStateChangeListener(watchID);
}
watchID = tizen.filesystem.addStorageStateChangeListener(onStorageStateChanged);
2.3. FileSystemStorage
The FileSystemStorage interface gives additional information about a storage, such as if the device is mounted, if it is a removable drive or not, or the device's name.
To retrieve the mount point, the resolve() method should be used using the label as argument.
Attributes
readonly DOMString label
The storage name.
This attribute is used as an input for methods such as getStorage() and also used as location parameter for File.resolve() and FileSystemManager.resolve().
Since: 1.0
readonly FileSystemStorageType type
The storage type as internal or external.
Since: 1.0
readonly FileSystemStorageState state
The storage state as mounted or not.
Since: 1.0
2.4. FileHandle
Object representing file, used for read/write operations.
Each read or write operation moves position in file forwards to the end of read/written data (there is an underlying file position's indicator).
Remark: Due to multibyte UTF-8 encoding, if current file's pointer does not point to beginning of multibyte sequence (see: UTF-16, emoji), using seek() combined with UTF-8 readString() will result in string starting from valid character. Incomplete byte sequence at the beginning may be omitted. Be aware about using seek and write methods together. It can result in writing in the middle of multibyte sequence, which can lead to file with corrupted content.
long long seek(long long offset, optional BaseSeekPosition whence);
Since: 5.0
Note, that current position indicator value, can be obtained by calling seek(0, "CURRENT").
Parameters:
offset: Number of bytes to shift the position relative to whence.
whence[optional]: Determines position in file stream to which offset is added. Default value: "BEGIN".
Return value:
long long: File position indicator.
Exceptions:
WebAPIException
with error type IOError, if seek fails or any error related to file handle occurs.
with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.
Code example:
var dataToWrite = new Uint8Array([11, 21, 31, 44, 55, 66, 71, 81, 91]);
/* Opening file for write - file is created if not exists, */
/* otherwise existing file is truncated. */
var fileHandleWrite = tizen.filesystem.openFile("documents/file", "w");
fileHandleWrite.writeData(dataToWrite);
fileHandleWrite.close();
console.log("Data has been written");
/* Opening file for read - this code assumes that there is */
/* a file named "file" in documents directory. */
var fileHandleRead = tizen.filesystem.openFile("documents/file", "r");
var firstThreeBytes = fileHandleRead.readData(3);
console.log("First three bytes: " + firstThreeBytes);
var position =
fileHandleRead.seek(-3, "END"); /* Moving to position three bytes to the end of file. */
var lastThreeBytes = fileHandleRead.readData(3);
console.log("Last three bytes: " + lastThreeBytes);
fileHandleRead.seek(3, "BEGIN"); /* Moving to position at third byte. */
var bytesBetween = fileHandleRead.readData(position - 3);
console.log("Bytes between: " + bytesBetween);
fileHandleRead.close();
Output example:
Data has been written
First three bytes: 11,21,31
Last three bytes: 71,81,91
Bytes between: 44,55,66
Successful seek operation invokes onsuccess function, if specified. In case of failure onerror function is invoked, if specified.
The ErrorCallback is launched with these error types:
IOError, if any error related to file handle occurs.
Note, that current position indicator value, can be obtained in SeekSuccessCallback by calling seekNonBlocking(0, "CURRENT"). seekNonBlocking is executed in background and does not block further instructions.
Parameters:
offset: Number of bytes to shift the position relative to whence.
onsuccess[optional][nullable]: Callback function to be invoked on success.
onerror[optional][nullable]: Callback function to be invoked when an error occurs.
whence[optional]: Determines position in file stream to which offset is added. Default value: "BEGIN".
Exceptions:
WebAPIException
with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.
Code example:
/* Opening file for write - file is created if not exists, */
/* otherwise existing file is truncated. */
var fileHandleWrite = tizen.filesystem.openFile("documents/file", "w");
fileHandleWrite.writeStringNonBlocking("Lorem ipsum dolor sit amet...",
function(bytesCount)
{
console.log("Number of bytes written: " + bytesCount);
},
function(error)
{
console.log(error);
});
/* Moving to position 3 bytes to the end of file to alter three dots ("..."). */
fileHandleWrite.seekNonBlocking(-3,
function(new_position)
{
console.log("Moved to position: " + new_position);
},
function(error)
{
console.log(error);
},
"END");
fileHandleWrite.writeStringNonBlocking(", consectetur adipiscing elit...",
function(bytesCount)
{
console.log("Number of bytes written: " + bytesCount);
},
function(error)
{
console.log(error);
});
/* Moving to position 3 bytes to the end of file to alter three dots ("..."). */
fileHandleWrite.seekNonBlocking(-3,
function(new_position)
{
console.log("Moved to position: " + new_position);
},
function(error)
{
console.log(error);
},
"END");
fileHandleWrite.writeStringNonBlocking(", sed do eiusmod...",
function(bytesCount)
{
console.log("Number of bytes written: " + bytesCount);
},
function(error)
{
console.log(error);
});
fileHandleWrite.closeNonBlocking(
function()
{
console.log("File handle closed");
},
function(error)
{
console.log(error);
});
/* Opening file for read - this code assumes that there is */
/* a file named "file" in documents directory. */
var fileHandleRead = tizen.filesystem.openFile("documents/file", "r");
/* ReadStringSuccessCallback should be executed. */
fileHandleRead.readStringNonBlocking(
function(output)
{
console.log("File content: " + output);
},
function(error)
{
console.log(error);
});
fileHandleRead.closeNonBlocking(
function()
{
console.log("File handle closed");
},
function(error)
{
console.log(error);
});
Output example:
Number of bytes written: 29
Moved to position: 26
Number of bytes written: 32
Moved to position: 55
Number of bytes written: 19
File handle closed
File content: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod...
File handle closed
readString
Reads file content as string.
DOMString readString(optional long long? count, optional DOMString inputEncoding);
Since: 5.0
Sets file handle position indicator at the end of read data. Reads given number of characters.
Remark: Resulting string can have length larger than count, due to possible UTF-16 surrogate pairs in it. String length in JavaScript is counted in UTF-16 encoding, so for example string containing one emoji (surrogate of two UTF-16) character will have length of two.
Parameters:
count[optional][nullable]: Number of characters to read from file. If none is given, method attempts to read whole file.
inputEncoding[optional]: Default value: "UTF-8". Encoding to use for read operation on the file, at least the following encodings must be supported:
with error type InvalidValuesError if given count exceeds maximum value supported by the device.
with error type IOError, if read fails or any error related to file handle occurs.
with error type NotSupportedError, if the given encoding is not supported.
with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.
Code example:
/* Opening file for write - file is created if not exists, */
/* otherwise existing file is truncated. */
var fileHandleWrite = tizen.filesystem.openFile("documents/file", "w");
console.log("File opened for writing");
fileHandleWrite.writeString("Lorem ipsum dolor sit amet...");
console.log("String has been written to the file");
fileHandleWrite.close();
/* Opening file for read - this code assumes that there is */
/* a file named "file" in documents directory. */
var fileHandleRead = tizen.filesystem.openFile("documents/file", "r");
console.log("File opened for reading");
var fileContent = fileHandleRead.readString();
console.log("File content: " + fileContent);
fileHandleRead.close();
Output example:
File opened for writing
String has been written to the file
File opened for reading
File content: Lorem ipsum dolor sit amet...
readStringNonBlocking
Reads file content as string.
void readStringNonBlocking(optional ReadStringSuccessCallback? onsuccess, optional ErrorCallback? onerror,
optional long long count, optional DOMString inputEncoding);
Since: 5.0
Reads given number of characters. Sets file handle position indicator at the end of read data. readStringNonBlocking is executed in background and does not block further instructions.
Successful read operation invokes onsuccess function, if specified. In case of failure onerror function is invoked, if specified.
The ErrorCallback is launched with these error types:
IOError, if read fails or any error related to file handle occurs.
Parameters:
onsuccess[optional][nullable]: Callback function with read data from file to be invoked on success.
onerror[optional][nullable]: Callback function to be invoked when an error occurs.
count[optional]: Number of characters to read from file. If none is given, method attempts to read whole file.
inputEncoding[optional]: Default value: "UTF-8". Encoding to use for read operation on the file, at least the following encodings must be supported:
with error type InvalidValuesError if given count exceeds maximum value supported by the device.
with error type NotSupportedError, if the given encoding is not supported.
with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.
Code example:
/* Opening file for write - file is created if not exists, */
/* otherwise existing file is truncated. */
var fileHandleWrite = tizen.filesystem.openFile("documents/file", "w");
console.log("File opened for writing");
fileHandleWrite.writeStringNonBlocking("Lorem ipsum dolor sit amet...",
function(bytesCount)
{
console.log("Number of bytes written: " + bytesCount);
},
function(error)
{
console.log(error);
});
fileHandleWrite.closeNonBlocking(
function()
{
console.log("File handle closed");
},
function(error)
{
console.log(error);
});
/* Opening file for read - below code assumes that there is */
/* a file named "file" in documents directory. */
var fileHandleRead = tizen.filesystem.openFile("documents/file", "r");
/* ReadStringSuccessCallback should be executed. */
fileHandleRead.readStringNonBlocking(
function(output)
{
console.log("File content: " + output);
},
function(error)
{
console.log(error);
});
fileHandleRead.closeNonBlocking(
function()
{
console.log("File handle closed");
},
function(error)
{
console.log(error);
});
Output example:
File opened for writing
Number of bytes written: 29
File handle closed
File content: Lorem ipsum dolor sit amet...
File handle closed
writeString
Writes inputString content to a file.
long long writeString(DOMString inputString, optional DOMString outputEncoding);
Since: 5.0
Sets file handle position indicator at the end of written data.
Parameters:
inputString: String value to be written to a file.
outputEncoding[optional]: Default value: UTF-8. Encoding to use for write operation on the file, at least the following encodings must be supported:
"UTF-8" default encoding
"ISO-8859-1" Latin-1 encoding
Return value:
long long: Number of bytes written (can be more than inputString length for multibyte encodings and will never be less)
Exceptions:
WebAPIException
with error type IOError, if input/output error occurs.
with error type NotSupportedError, if the given encoding is not supported.
Code example:
/* Opening file for write - file is created if not exists, */
/* otherwise existing file is truncated. */
var fileHandleWrite = tizen.filesystem.openFile("documents/file", "w");
console.log("File opened for writing");
fileHandleWrite.writeString("Lorem ipsum dolor sit amet...");
console.log("String has been written to the file");
fileHandleWrite.close();
/* Opening file for read - this code assumes that there is */
/* a file named "file" in documents directory. */
var fileHandleRead = tizen.filesystem.openFile("documents/file", "r");
console.log("File opened for reading");
var fileContent = fileHandleRead.readString();
console.log("File content: " + fileContent);
fileHandleRead.close();
Output example:
File opened for writing
String has been written to the file
File opened for reading
File content: Lorem ipsum dolor sit amet...
Sets file handle position indicator at the end of written data. writeStringNonBlocking is executed in background and does not block further instructions.
Successful write operation invokes successCallback function, if specified. In case of failure onerror function is invoked, if specified.
The ErrorCallback is launched with these error types:
IOError, if write fails or any error related to file handle occurs.
Parameters:
inputString: String value to be written to a file.
onsuccess[optional][nullable]: Callback function with a number of bytes written as parameter to be invoked on success.
onerror[optional][nullable]: Callback function to be invoked when an error occurs.
outputEncoding [optional]: Default value: "UTF-8". Encoding to use for write operation on the file, at least the following encodings must be supported:
"UTF-8" default encoding
"ISO-8859-1" Latin-1 encoding
Exceptions:
WebAPIException
with error type NotSupportedError, if the given encoding is not supported.
with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.
Code example:
/* Opening file for write - file is created if not exists, */
/* otherwise existing file is truncated. */
var fileHandleWrite = tizen.filesystem.openFile("documents/file", "w");
fileHandleWrite.writeStringNonBlocking("Lorem ipsum dolor sit amet...",
function(bytesCount)
{
console.log("Number of bytes written: " + bytesCount);
},
function(error)
{
console.log(error);
});
fileHandleWrite.closeNonBlocking(
function()
{
console.log("File handle closed");
},
function(error)
{
console.log(error);
});
/* Opening file for read - below code assumes that there is */
/* a file named "file" in documents directory. */
var fileHandleRead = tizen.filesystem.openFile("documents/file", "r");
/* ReadStringSuccessCallback should be executed. */
fileHandleRead.readStringNonBlocking(
function(output)
{
console.log("File content: " + output);
},
function(error)
{
console.log(error);
});
fileHandleRead.closeNonBlocking(
function()
{
console.log("File handle closed");
},
function(error)
{
console.log(error);
});
Output example:
Number of bytes written: 29
File handle closed
File content: Lorem ipsum dolor sit amet...
File handle closed
Sets file handle position indicator at the end of read data.
Parameters:
size[optional]: Size in bytes of data to read from file. If none is given, method attempts to read whole file.
Return value:
Blob: Blob object with file content.
Exceptions:
WebAPIException
with error type InvalidValuesError if given size exceeds maximum value supported by the device.
with error type IOError, if read fails or any error related to file handle occurs.
Code example:
/* Opening file for write - file is created if not exists, */
/* otherwise existing file is truncated. */
var fileHandleWrite = tizen.filesystem.openFile("documents/file", "w");
var b = new Blob(["Lorem ipsum dolor sit amet..."], {type: "text/plain"});
fileHandleWrite.writeBlob(b);
fileHandleWrite.close();
console.log("Blob content has been written to file");
/* Opening file for read - this code assumes that there is */
/* a file named "file" in documents directory. */
var fileHandleRead = tizen.filesystem.openFile("documents/file", "r");
var fileContentInBlob = fileHandleRead.readBlob();
fileHandleRead.close();
const reader = new FileReader();
/* Event fires after the blob has been read/loaded. */
reader.onloadend = function(content)
{
const text = content.srcElement.result;
console.log("File content: " + text);
};
/* Starts reading the blob as text. */
reader.readAsText(fileContentInBlob);
Output example:
Blob content has been written to file
File content: Lorem ipsum dolor sit amet...
Sets file handle position indicator at the end of read data. readBlobNonBlocking is executed in background and does not block further instructions.
Successful read operation invokes onsuccess function, if specified. In case of failure onerror function is invoked, if specified.
The ErrorCallback is launched with these error types:
IOError, if read fails or any error related to file handle occurs.
Parameters:
onsuccess[optional][nullable]: Callback function with Blob object to be invoked on success.
onerror[optional][nullable]: Callback function to be invoked when an error occurs.
size[optional][nullable]: Size in bytes of data to read from file. If none is given, method attempts to read whole file.
Exceptions:
WebAPIException
with error type InvalidValuesError if given size exceeds maximum value supported by the device.
with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.
Code example:
/* Opening file for write - file is created if not exists, */
/* otherwise existing file is truncated. */
var fileHandleWrite = tizen.filesystem.openFile("documents/file", "w");
var b = new Blob(["Lorem ipsum dolor sit amet..."], {type: "text/plain"});
fileHandleWrite.writeBlobNonBlocking(b,
function()
{
console.log("Blob content has been written to file");
},
function(error)
{
console.log(error);
});
fileHandleWrite.closeNonBlocking(
function()
{
console.log("File handle closed");
},
function(error)
{
console.log(error);
});
/* Opening file for read - this code assumes that there is */
/* a file named "file" in documents directory. */
var fileHandleRead = tizen.filesystem.openFile("documents/file", "r");
/* Creation of a reader capable of extracting Blob content. */
const reader = new FileReader();
/* Event fires after the blob has been read/loaded. */
reader.onloadend = function(content)
{
const text = content.srcElement.result;
console.log("File content: " + text);
};
function readBlobCallback(fileContentInBlob)
{
reader.readAsText(fileContentInBlob);
}
/* readBlobCallback should be executed. */
fileHandleRead.readBlobNonBlocking(readBlobCallback, function(error)
{
console.log(error);
});
fileHandleRead.closeNonBlocking(
function()
{
console.log("File handle closed");
},
function(error)
{
console.log(error);
});
Output example:
Blob content has been written to file
File handle closed
File handle closed
File content: Lorem ipsum dolor sit amet...
Sets file handle position indicator at the end of written data.
Parameters:
blob: Object of type Blob, which content will be written to a file.
Exceptions:
WebAPIException
with error type IOError, if write fails or any error related to file handle occurs.
with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.
Code example:
/* Opening file for write - file is created if not exists, */
/* otherwise existing file is truncated. */
var fileHandleWrite = tizen.filesystem.openFile("documents/file", "w");
var b = new Blob(["Lorem ipsum dolor sit amet..."], {type: "text/plain"});
fileHandleWrite.writeBlob(b);
fileHandleWrite.close();
console.log("Blob content has been written to file");
/* Opening file for read - this code assumes that there is */
/* a file named "file" in documents directory. */
var fileHandleRead = tizen.filesystem.openFile("documents/file", "r");
var fileContentInBlob = fileHandleRead.readBlob();
fileHandleRead.close();
console.log("File content has been read from file");
const reader = new FileReader();
/* Event fires after the blob has been read/loaded. */
reader.onloadend = function(content)
{
const text = content.srcElement.result;
console.log("File content: " + text);
};
/* Starts reading the blob as text. */
reader.readAsText(fileContentInBlob);
Output example:
Blob content has been written to file
File content has been read from file
File content: Lorem ipsum dolor sit amet...
Sets file handle position indicator at the end of written data. writeBlobNonBlocking is executed in background and does not block further instructions.
Successful write operation invokes onsuccess function, if specified. In case of failure onerror function is invoked, if specified.
The ErrorCallback is launched with these error types:
IOError, if write fails or any error related to file handle occurs.
Parameters:
blob: Object of type Blob, which content will be written to a file.
onsuccess[optional][nullable]: Callback function to be invoked on success.
onerror[optional][nullable]: Callback function to be invoked when an error occurs.
Exceptions:
WebAPIException
with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.
Code example:
/* Opening file for write - file is created if not exists, */
/* otherwise existing file is truncated. */
var fileHandleWrite = tizen.filesystem.openFile("documents/file", "w");
var b = new Blob(["Lorem ipsum dolor sit amet..."], {type: "text/plain"});
fileHandleWrite.writeBlobNonBlocking(b,
function()
{
console.log("Blob content has been written to file");
},
function(error)
{
console.log(error);
});
fileHandleWrite.closeNonBlocking(
function()
{
console.log("File handle closed");
},
function(error)
{
console.log(error);
});
/* Opening file for read - this code assumes that there is */
/* a file named "file" in documents directory. */
var fileHandleRead = tizen.filesystem.openFile("documents/file", "r");
/* Creation of a reader capable of extracting Blob content. */
const reader = new FileReader();
/* Event fires after the blob has been read/loaded. */
reader.onloadend = function(content)
{
const text = content.srcElement.result;
console.log("File content: " + text);
};
function readBlobCallback(fileContentInBlob)
{
reader.readAsText(fileContentInBlob);
}
/* readBlobCallback should be executed. */
fileHandleRead.readBlobNonBlocking(readBlobCallback);
fileHandleRead.closeNonBlocking(
function()
{
console.log("File handle closed");
},
function(error)
{
console.log(error);
});
Output example:
Blob content has been written to file
File handle closed
File handle closed
File content: Lorem ipsum dolor sit amet...
readData
Reads file content as binary data.
Uint8Array readData(optional long long size);
Since: 5.0
Can be used in combination with atob() or btoa() functions. Sets file handle position indicator at the end of read data.
Parameters:
size[optional]: Size in bytes of data to read from file. If none is given, method attempts to read whole file.
Return value:
Uint8Array: Read data as Uint8Array.
Exceptions:
WebAPIException
with error type InvalidValuesError if given size exceeds maximum value supported by the device.
with error type IOError, if read fails or any error related to file handle occurs.
Code example:
var dataToWrite = new Uint8Array([11, 21, 31, 71, 81, 91]);
/* Opening file for write - file is created if not exists, */
/* otherwise existing file is truncated. */
var fileHandleWrite = tizen.filesystem.openFile("documents/file", "w");
fileHandleWrite.writeData(dataToWrite);
fileHandleWrite.close();
console.log("Data has been written");
/* Opening file for read - below code assumes that there is */
/* a file named "file" in documents directory. */
var fileHandleRead = tizen.filesystem.openFile("documents/file", "r");
var fileContentInUint8Array = fileHandleRead.readData();
fileHandleRead.close();
console.log("Data read from file: " + fileContentInUint8Array);
Output example:
Data has been written
Data read from file: 11,21,31,71,81,91
Can be used in combination with atob() or btoa() functions. Sets file handle position indicator at the end of read data. readDataNonBlocking is executed in background and does not block further instructions.
Successful read operation invokes onsuccess function, if specified. In case of failure onerror function is invoked, if specified.
The ErrorCallback is launched with these error types:
IOError, if read fails or any error related to file handle occurs.
Parameters:
onsuccess[optional][nullable]: Callback function with read data from file to be invoked on success.
onerror[optional][nullable]: Callback function to be invoked when an error occurs.
size[optional][nullable]: Size in bytes of data to read from file. If none is given, method attempts to read whole file.
Exceptions:
WebAPIException
with error type InvalidValuesError if given size exceeds maximum value supported by the device.
with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.
Code example:
var dataToWrite = new Uint8Array([11, 21, 31, 71, 81, 91]);
/* Opening file for write - file is created if not exists, */
/* otherwise existing file is truncated. */
var fileHandleWrite = tizen.filesystem.openFile("documents/file", "w");
fileHandleWrite.writeDataNonBlocking(dataToWrite,
function(dataRead)
{
console.log("Write done");
},
function(error)
{
console.log(error);
});
fileHandleWrite.closeNonBlocking(
function()
{
console.log("File handle closed");
},
function(error)
{
console.log(error);
});
/* Opening file for read - below code assumes that there is */
/* a file named "file" in documents directory. */
var fileHandleRead = tizen.filesystem.openFile("documents/file", "r");
fileHandleRead.readDataNonBlocking(
function(dataRead)
{
console.log("Data read from file: " + dataRead);
},
function(error)
{
console.log(error);
});
fileHandleRead.closeNonBlocking(
function()
{
console.log("File handle closed");
},
function(error)
{
console.log(error);
});
Output example:
Write done
File handle closed
Data read from file: 11,21,31,71,81,91
File handle closed
writeData
Writes binary data to file.
void writeData(Uint8Array data);
Since: 5.0
Can be used in combination with atob() or btoa() functions. Sets file handle position indicator at the end of written data.
Parameters:
data: An array of type Uint8Array, which content will be written to file as binary data.
Exceptions:
WebAPIException
with error type IOError, if write fails or any error related to file handle occurs.
with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.
Code example:
var dataToWrite = new Uint8Array([11, 21, 31, 71, 81, 91]);
/* Opening file for write - file is created if not exists, */
/* otherwise existing file is truncated. */
var fileHandleWrite = tizen.filesystem.openFile("documents/file", "w");
fileHandleWrite.writeData(dataToWrite);
fileHandleWrite.close();
console.log("Data has been written");
/* Opening file for read - below code assumes that there is */
/* a file named "file" in documents directory. */
var fileHandleRead = tizen.filesystem.openFile("documents/file", "r");
var fileContentInUint8Array = fileHandleRead.readData();
fileHandleRead.close();
console.log("Data read from file: " + fileContentInUint8Array);
Output example:
Data has been written
Data read from file: 11,21,31,71,81,91
Can be used in combination with atob() or btoa() functions. Sets file handle position indicator at the end of written data. writeDataNonBlocking is executed in background and does not block further instructions.
Successful write operation invokes onsuccess function, if specified. In case of failure onerror function is invoked, if specified.
The ErrorCallback is launched with these error types:
IOError, if write fails or any error related to file handle occurs.
Parameters:
data: An array of type Uint8Array, which content will be written to file as binary data.
onsuccess[optional][nullable]: Callback function to be invoked on success.
onerror[optional][nullable]: Callback function to be invoked when an error occurs.
Exceptions:
WebAPIException
with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.
Code example:
var dataToWrite = new Uint8Array([11, 21, 31, 71, 81, 91]);
/* Opening file for write - file is created if not exists, */
/* otherwise existing file is truncated. */
var fileHandleWrite = tizen.filesystem.openFile("documents/file", "w");
fileHandleWrite.writeDataNonBlocking(dataToWrite,
function(dataRead)
{
console.log("Write done");
},
function(error)
{
console.log(error);
});
fileHandleWrite.closeNonBlocking(
function()
{
console.log("File handle closed");
},
function(error)
{
console.log(error);
});
/* Opening file for read - below code assumes that there is */
/* a file named "file" in documents directory. */
var fileHandleRead = tizen.filesystem.openFile("documents/file", "r");
fileHandleRead.readDataNonBlocking(
function(dataRead)
{
console.log("Data read from file: " + dataRead);
},
function(error)
{
console.log(error);
});
fileHandleRead.closeNonBlocking(
function()
{
console.log("File handle closed");
},
function(error)
{
console.log(error);
});
Output example:
Write done
File handle closed
Data read from file: 11,21,31,71,81,91
File handle closed
flush
Flushes data.
void flush();
Since: 5.0
For file handles with permission to write, flush writes any changes made to file content to underlying buffer.
Flush does not ensure that data is written on storage device, it only synchronizes RAM with file descriptor. To ensure storage synchronization use sync, close or their asynchronous equivalent methods, which guarantee such synchronization.
Exceptions:
WebAPIException
with error type IOError, if flush fails or any error related to file handle occurs.
Code example:
/* Opening file for write - file is created if not exists, */
/* otherwise existing file is truncated. */
var fileHandleWrite = tizen.filesystem.openFile("documents/file", "w");
var fileHandleRead = tizen.filesystem.openFile("documents/file", "r");
fileHandleWrite.writeString("Lorem ipsum dolor sit amet...");
console.log("Data has been written to file");
/* Calling flush() ensures that content has been written to file descriptor and can be read by any */
/* process. */
fileHandleWrite.flush();
console.log("Data has been flushed to system file buffer and now can be read");
var fileContent = fileHandleRead.readString();
console.log("Read data: " + fileContent);
fileHandleWrite.close();
fileHandleRead.close();
Output example:
Data has been written to file
Data has been flushed to system file buffer and now can be read
Read data: Lorem ipsum dolor sit amet...
For file handles with permission to write, flush writes any changes made to file content to underlying buffer.
Flush does not ensure that data is written on storage device, it only synchronizes RAM with file descriptor. To ensure storage synchronization use sync, close or their asynchronous equivalent methods, which guarantee such synchronization.
Successful flushing invokes onsuccess function, if specified. In case of failure onerror function is invoked, if specified.
The ErrorCallback is launched with these error types:
IOError, if flush fails or any error related to file handle occurs.
This method is asynchronous. Its execution will occur in background and after all previously commissioned background jobs will finish.
Parameters:
onsuccess[optional][nullable]: Callback function to be invoked on success.
onerror[optional][nullable]: Callback function to be invoked when an error occurs.
Exceptions:
WebAPIException
with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.
Code example:
/* Opening file for write - file is created if not exists, */
/* otherwise existing file is truncated. */
var fileHandleWrite = tizen.filesystem.openFile("documents/file", "w");
fileHandleWrite.writeStringNonBlocking("Lorem ipsum dolor sit amet...",
function(bytesCount)
{
console.log("Number of bytes written: " + bytesCount);
},
function(error)
{
console.log(error);
});
/* Calling flushNonBlocking() ensures that content will be written to file descriptor */
/* and can be read by any process. */
fileHandleWrite.flushNonBlocking(
function()
{
console.log("Data has been flushed to system file buffer and now can be read");
},
function(error)
{
console.log(error);
});
/* Opening file for read - this code assumes that there is */
/* a file named "file" in documents directory. */
var fileHandleRead = tizen.filesystem.openFile("documents/file", "r");
fileHandleRead.readStringNonBlocking(
function(output)
{
console.log("File content: " + output);
},
function(error)
{
console.log(error);
});
fileHandleWrite.closeNonBlocking(
function()
{
console.log("File handle closed");
},
function(error)
{
console.log(error);
});
fileHandleRead.closeNonBlocking(
function()
{
console.log("File handle closed");
},
function(error)
{
console.log(error);
});
Output example:
Number of bytes written: 29
Data has been flushed to system file buffer and now can be read
File content: Lorem ipsum dolor sit amet...
File handle closed
File handle closed
sync
Synchronizes data to storage device.
void sync();
Since: 5.0
The sync function is intended to force a physical write of data from the buffer cache and to assure that after a system crash or other failure that all data up to the time of the sync() call is recorded on the disk.
Exceptions:
WebAPIException
with error type IOError, if sync fails or any error related to file handle occurs.
Code example:
var dataToWrite = new Uint8Array([11, 21, 31, 71, 81, 91]);
/* Opening file for write - file is created if not exists, */
/* otherwise existing file is truncated. */
var fileHandleWrite = tizen.filesystem.openFile("documents/file", "w");
fileHandleWrite.writeData(dataToWrite);
/* Calling sync() forces a physical write of data, so it is safe */
/* even after system crash or power shut down. */
fileHandleWrite.sync();
console.log("Data has been synced");
/* close() method provides the same functionality as sync() and ends access to file. */
fileHandleWrite.close();
Output example:
Data has been synced
**syncNonBlocking
**
Synchronizes data to storage device.
The syncNonBlocking function is intended to force a physical write of data from the buffer cache and to assure that after a system crash or other failure that all data up to the time of the syncNonBlocking() execution is recorded on the disk.
Successful syncing invokes onsuccess function, if specified. In case of failure onerror function is invoked, if specified.
The ErrorCallback is launched with these error types:
IOError, if sync fails or any error related to file handle occurs.
This method is asynchronous. Its execution will occur in background and after all previously commissioned background jobs will finish.
Parameters:
onsuccess[optional][nullable]: Callback function to be invoked on success.
onerror[optional][nullable]: Callback function to be invoked when an error occurs.
Exceptions:
WebAPIException
with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.
Code example:
var dataToWrite = new Uint8Array([11, 21, 31, 71, 81, 91]);
/* Opening file for write - file is created if not exists, */
/* otherwise existing file is truncated. */
var fileHandleWrite = tizen.filesystem.openFile("documents/file", "w");
fileHandleWrite.writeDataNonBlocking(dataToWrite,
function(dataRead)
{
console.log("Write done");
},
function(error)
{
console.log(error);
});
/* Calling syncNonBlocking() will force a physical write of data, so it will be safe */
/* even after system crash or power shut down. */
fileHandleWrite.syncNonBlocking(
function()
{
console.log("Data has been synced");
},
function(error)
{
console.log(error);
});
/* close() method provides the same functionality as sync() and ends access to file. */
fileHandleWrite.closeNonBlocking(
function()
{
console.log("File handle closed");
},
function(error)
{
console.log(error);
});
Output example:
Write done
Data has been synced
File handle closed
close
Closes file handle.
void close();
Since: 5.0
Closes the given file stream. Closing file guarantees writing changes made to FileHandle to the storage device. Further operations on this file handle are not allowed.
Remark: This method is synchronous. If any asynchronous method was called before close, close will block further instructions until all background jobs finish execution. Note, that if file handle functions are put into any callbacks and this callback was not yet called, synchronous close will wait only for already ordered background jobs to finish, preventing successful execution of any further operations on closed file handle.
Exceptions:
WebAPIException
with error type IOError, if close fails or any error related to file handle occurs.
Code example:
/* Opening file for write - file is created if not exists, */
/* otherwise existing file is truncated. */
var fileHandleWrite = tizen.filesystem.openFile("documents/file", "w");
fileHandleWrite.writeString("Lorem ipsum dolor sit amet...");
fileHandleWrite.close();
console.log("String has been written to the file");
/* Opening file for read - this code assumes that there is */
/* a file named "file" in documents directory. */
var fileHandleRead = tizen.filesystem.openFile("documents/file", "r");
var positionOfFileEnd = fileHandleRead.seek(0, "END");
console.log("Seek operation done. Position of file end: " + positionOfFileEnd);
fileHandleRead.close();
console.log("File is now closed");
Output example:
String has been written to the file
Seek operation done. Position of file end: 29
File is now closed
Closes the given file stream. Closing file guarantees writing changes made to FileHandle to the storage device. Further operations on this file handle are not allowed.
Successful closing invokes onsuccess function, if specified. In case of failure onerror function is invoked, if specified.
The ErrorCallback is launched with these error types:
IOError, if close fails or any error related to file handle occurs.
This method is asynchronous. Its execution will occur in background and after all previously commissioned background jobs will finish.
Parameters:
onsuccess[optional][nullable]: Callback function to be invoked on success.
onerror[optional][nullable]: Callback function to be invoked when an error occurs.
Exceptions:
WebAPIException
with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.
Code example:
/* Opening file for write - file is created if not exists, */
/* otherwise existing file is truncated. */
var fileHandleWrite = tizen.filesystem.openFile("documents/file", "w");
fileHandleWrite.writeStringNonBlocking("Lorem ipsum dolor sit amet...",
function(bytesCount)
{
console.log("Number of bytes written: " + bytesCount);
},
function(error)
{
console.log(error);
});
fileHandleWrite.closeNonBlocking(
function()
{
console.log("File handle closed");
},
function(error)
{
console.log(error);
});
/* Opening file for read - this code assumes that there is */
/* a file named "file" in documents directory. */
var fileHandleRead = tizen.filesystem.openFile("documents/file", "r");
var positionOfFileEnd = fileHandleRead.seekNonBlocking(0,
function(new_position)
{
console.log("Moved to position: " + new_position);
},
function(error)
{
console.log(error);
},
"END");
fileHandleRead.closeNonBlocking(
function()
{
console.log("File handle closed");
},
function(error)
{
console.log(error);
});
Output example:
Number of bytes written: 29
File handle closed
Moved to position: 29
File handle closed
2.5. File
The File interface represents the file abstraction in use.
The file object permissions for the file object location and tree rooted at that location depend upon the mode defined in the resolve method. When a File object creates a child File object, the new File object inherits its access rights from the parent object without any reference to the security framework, as noted in certain methods of File.
A file handle represents either a file or a directory:
For a file, the isFile attribute is set to true.
For a directory, the isDirectory attribute is set to true.
A file can be opened for both read and write operations, using a FileStream handle. A list of files and sub-directories can be obtained from a directory and a resolve method exists to resolve files or sub-directories more conveniently than processing directory listings.
A file handle representing a file can be opened for I/O operations, such as reading and writing.
A file handle representing a directory can be used for listing all files and directories rooted as the file handle location.
Code example:
function onsuccess(files)
{
for (var i = 0; i < files.length; i++)
{
/* Alerts each name of dir's content. */
console.log(files[i].name);
}
}
function onerror(error)
{
console.log(
"The error " + error.message + " occurred when listing the files in the selected folder");
}
/* List directory content. */
dir.listFiles(onsuccess, onerror);
Attributes
readonly File parent [nullable]
The parent directory handle.
Deprecated. Since 5.0
This attribute is set to null if there is no parent directory. This also implies that this directory represents a root location.
Since: 1.0
Code example:
/* List directory content. */
dir.listFiles(onsuccess, onerror);
function onsuccess(files)
{
for (var i = 0; i < files.length; i++)
{
/* Prints the file parent, must contain the */
/* same value for all the files in the loop. */
console.log("All the files should have the same parent " + files[i].parent);
}
}
function onerror(error)
{
console.log(
"The error " + error.message + " occurred when listing the files in the selected folder");
}
readonly boolean readOnly
The file/directory access state in the filesystem.
Deprecated. Since 5.0
This attribute is set to:
true - if object has read-only access at its location.
false - if object has write access at its location.
This attribute represents the actual state of a file or directory in the filesystem. Its value is not affected by the mode used in FileSystemManager.resolve() that was used to create the File object from which this File object was obtained.
Since: 1.0
Code example:
/* Lists directory content. */
dir.listFiles(onsuccess, onerror);
function onsuccess(files)
{
for (var i = 0; i < files.length; i++)
{
if (files[i].readOnly)
console.log("Cannot write to file " + files[i].name);
else
console.log("Can write to file " + files[i].name);
}
}
function onerror(error)
{
console.log(
"The error " + error.message + " occurred when listing the files in the selected folder");
}
readonly boolean isFile
The flag indicating whether it is a file.
Deprecated. Since 5.0
This attribute can have the following values:
true if this handle is a file
false if this handle is a directory
Since: 1.0
readonly boolean isDirectory
The flag indicating whether it is a directory.
Deprecated. Since 5.0
This attribute can have the following values:
true if this handle is a directory
false if this handle is a file
Since: 1.0
readonly Date created [nullable]
The timestamp when a file is first created in the filesystem.
Deprecated. Since 5.0
This timestamp is equivalent to the timestamp when a call to createFile() succeeds.
If the platform does not support this attribute, it will be null.
It is unspecified and platform-dependent if the creation timestamp changes when a file is moved.
Since: 1.0
readonly Date modified [nullable]
The timestamp when the most recent modification is made to a file, usually when the last write operation succeeds.
Deprecated. Since 5.0
Opening a file for reading does not change the modification timestamp.
If the platform does not support this attribute, it will be null.
It is unspecified and platform-dependent if the modified timestamp changes when a file is moved.
Since: 1.0
Code example:
console.log(file.modified); /* Displays the modification timestamp. */
readonly DOMString path
The path of a file after excluding its file name.
Deprecated. Since 5.0
It begins with the name of the root containing the file, followed by the path, including the directory containing the file, but excluding the file name.
Except in some special cases of the File representing the root itself, the last character is always "/".
For example, if a file is located at music/ramones/volume1/RockawayBeach.mp3, the path is music/ramones/volume1/.
For example, if a directory is located at music/ramones/volume1, the path is music/ramones/.
For the virtual roots, the path is same as the name of the virtual root. For example, if the root is music, then the path is music. If the root is documents, then the path is documents.
Since: 1.0
Code example:
console.log(file.path); /* Must be music/ if the file is music/foo.mp3. */
readonly DOMString name
The file name after excluding the root name and any path components.
Deprecated. Since 5.0
This is the name of this file, excluding the root name and any other path components.
For example, if a file is located at music/ramones/volume1/RockawayBeach.mp3, the name is "RockawayBeach.mp3".
For example, if a directory is located at music/ramones/volume1, the name is be "volume1".
For the special case of the root itself, the name is an empty string.
Since: 1.0
Code example:
/* Must be foo.mp3 if the file path is music/foo.mp3. */
console.log(file.name);
readonly DOMString fullPath
The full path of a file.
Deprecated. Since 5.0
It begins with the name of the root containing the file, and including the name of the file or directory itself.
For instance, if the RockawayBeach.mp3 file is located at music/ramones/volume1/, then the fullPath is music/ramones/volume1/RockawayBeach.mp3.
For a directory, if the volume1 directory is located at music/ramones/, then the fullPath is music/ramones/volume1.
For the special case of the root itself, if the root is music, then the fullPath is music.
The fullPath is always equal to path + name.
Since: 1.0
Code example:
/* Must be music/track1.mp3 if the file is music/track1.mp3. */
console.log(file.fullPath);
readonly unsigned long long fileSize
The size of this file, in bytes.
Deprecated. Since 5.0
If an attempt to read this attribute for a directory is made, undefined is returned. To retrieve the number of files and directories contained in the directory, use the length attribute.
Since: 1.0
Code example:
/* Displays the file size. */
console.log(file.fileSize);
readonly long length
The number of files and directories contained in a file handle.
Deprecated. Since 5.0
If an attempt to read this attribute for a file is made, undefined is returned. To retrieve the size of a file, use the fileSize attribute.
Since: 1.0
Code example:
/* "3" if the directory contains two files and one sub-directory. */
console.log(file.length);
Methods
toURI
Returns a URI for a file to identify an entry (such as using it as the src attribute on an HTML img element). The URI has no specific expiration, it should be valid at least as long as the file exists.
Deprecated. Since 5.0
DOMString toURI();
Since: 1.0
If that URI corresponds to any of the public virtual roots (that is images, videos, music, documents and downloads) the URI must be globally unique and could be used by any widget.
If that URI corresponds to a file located in any a widget's private areas (such as wgt-package, wgt-private, wgt-private-tmp), the generated URI must be unique for that file and for the widget making the request (such as including some derived from the widget ID in the URI). These URIs must not be accessible to other widgets, apart from the one invoking this method.
The list of files is passed as a File[] in onsuccess() and contains directories and files. However, the directories "." and ".." must not be returned. Each File object that is part of the array must inherit all the access rights (that is, one of the values in FileMode) from the File object in which this method is invoked.
If the filter is passed and contains valid values, only those directories and files in the directory that match the filter criteria specified in the FileFilter interface must be returned in the onsuccess() method. If no filter is passed, the filter is null or undefined, or the filter contains invalid values, the implementation must return the full list of files in the directory.
If the directory does not contain any files or directories, or the filter criteria do not match any files or directories, the onsuccess() is invoked with an empty array.
The ErrorCallback is launched with these error types:
IOError - If the operation is launched on a file (not a directory).
InvalidValuesError - If any of the input parameters contain an invalid value.
onsuccess: Callback method to be invoked when the list operation has been successfully completed.
onerror[optional][nullable]: Callback method to be invoked when an error has occurred.
filter[optional][nullable]: Criteria to restrict the listed files.
Exceptions:
WebAPIException
with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.
with error type SecurityError, if the application does not have the privilege to call this method. For more information, see Storage privileges.
Code example:
function onsuccess(files)
{
console.log("There are " + files.length + " in the selected folder");
}
function onerror(error)
{
console.log(
"The error " + error.message + " occurred when listing the files in the selected folder");
}
tizen.filesystem.resolve("documents",
function(dir)
{
dir.listFiles(onsuccess, onerror);
},
function(e)
{
console.log("Error " + e.message);
},
"r");
openStream
Opens the file in the given mode supporting a specified encoding.
This operation is performed asynchronously. If the file is opened successfully, the onsuccess() method is invoked with a FileStream that can be used for reading and writing the file, depending on the mode. The returned FileStream instance includes a file pointer, which represents the current position in the file. The file pointer, by default, is at the start of the file, except in the case of opening a file in append ("a") mode, in which case the file pointer points to the end of the file.
The ErrorCallback is launched with these error types:
InvalidValuesError - If any of the input parameters contains an invalid value.
IOError - The operation is launched on a directory (not a file), the file is not valid or it does not exist.
If no encoding is passed by the developer, then the default platform encoding must be used.
Exceptions:
WebAPIException
with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.
with error type SecurityError, if the application does not have the privilege to call this method or the application does not have privilege to access the storage. For more information, see Storage privileges.
Code example:
var documentsDir;
function onsuccess(files)
{
for (var i = 0; i < files.length; i++)
{
console.log("File Name is " + files[i].name); /* Displays file name. */
}
var testFile = documentsDir.createFile("test.txt");
if (testFile != null)
{
testFile.openStream("w",
function(fs)
{
fs.write("HelloWorld");
fs.close();
},
function(e)
{
console.log("Error " + e.message);
},
"UTF-8");
}
}
function onerror(error)
{
console.log(
"The error " + error.message + " occurred when listing the files in the selected folder");
}
tizen.filesystem.resolve("documents",
function(dir)
{
documentsDir = dir;
dir.listFiles(onsuccess, onerror);
},
function(e)
{
console.log("Error " + e.message);
},
"rw");
If the operation is successfully executed, the onsuccess() method is invoked and a DOMString is passed as input parameter that represents the file content in the format determined by the encoding parameter.
The ErrorCallback is launched with these error types:
InvalidValuesError - If any of the input parameters contains an invalid value.
IOError - If the operation is launched on a directory (not a file), the file is not valid, or the file does not exist.
The copy of the file or directory identified by the originFilePath parameter must be created in the path passed in the destinationFilePath parameter.
The file or directory to copy must be under the Directory from which the method is invoked, otherwise the operation must not be performed.
If the copy is performed successfully, the onsuccess() method is invoked.
The ErrorCallback is launched with these error types:
InvalidValuesError - If any of the input parameters contains an invalid value.
NotFoundError - If the originFilePath does not correspond to a valid file or destinationPath is not a valid path.
IOError - If the file in which the copyTo() method is invoked is a file (and not a directory), originFilePath corresponds to a file or directory in use by another process, overwrite parameter is false and destinationFilePath corresponds to an existing file or directory.
originFilePath: Origin full virtual file or directory path and it must be under the current directory.
destinationFilePath: New full virtual file path or directory path.
overwrite: Attribute to determine whether overwriting is allowed or not
If set to true, it enforces overwriting an existing file.
onsuccess[optional][nullable]: Callback method to be invoked when the file has been copied.
onerror[optional][nullable]: Callback method to be invoked when an error has occurred.
Exceptions:
WebAPIException
with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.
with error type SecurityError, if the application does not have the privilege to call this method or the application does not have privilege to access the storage. For more information, see Storage privileges.
Code example:
var documentsDir;
function onsuccess(files)
{
for (var i = 0; i < files.length; i++)
{
if (files[i].isDirectory == false)
{
documentsDir.copyTo(files[i].fullPath, "images/backup/" + files[i].name, false, function()
{
console.log("File copied");
});
}
}
}
function onerror(error)
{
console.log(
"The error " + error.message + " occurred when listing the files in the selected folder");
}
tizen.filesystem.resolve("documents",
function(dir)
{
documentsDir = dir;
dir.listFiles(onsuccess, onerror);
},
function(e)
{
console.log("Error " + e.message);
},
"rw");
moveTo
Moves (and overwrites if possible and specified) a file or a directory from a specified location to another. This operation is different from instantiating copyTo() and then deleting the original file, as on certain platforms, this operation does not require extra disk space.
The file or directory identified by the originFilePath parameter is moved to the path passed in the destinationFilePath parameter.
The file to move must be under the directory from which the method is invoked, else the operation can not be performed.
If the file or directory is moved successfully, the onsuccess() method is invoked.
The ErrorCallback is launched with these error types:
InvalidValuesError - If any of the input parameters contains an invalid value.
NotFoundError - If originFilePath does not correspond to a valid file or destinationPath is not a valid path.
IOError - If the File in which the moveTo() method is invoked is a file (not a directory), originFilePath corresponds to a file or directory in use by another process, overwrite parameter is false and destinationFilePath corresponds to an existing file or directory.
originFilePath: Origin full virtual file or directory path and it must be under the current directory.
destinationFilePath: New full virtual file path or directory path.
overwrite: Flag indicating whether to overwrite an existing file.
When set to true, the files can be overwritten.
onsuccess[optional][nullable]: Callback method to be invoked when the file has been moved.
onerror[optional][nullable]: Callback method to be invoked when an error has occurred.
Exceptions:
WebAPIException
with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.
with error type SecurityError, if the application does not have the privilege to call this method or the application does not have privilege to access the storage. For more information, see Storage privileges.
Code example:
var documentsDir;
function onsuccess(files)
{
for (var i = 0; i < files.length; i++)
{
if (files[i].isDirectory == false)
{
documentsDir.moveTo(
files[i].fullPath, "images/newFolder/" + files[i].name, false, function()
{
console.log("File moved");
});
}
}
}
function onerror(error)
{
console.log(
"The error " + error.message + " occurred during listing the files in the selected folder");
}
tizen.filesystem.resolve("documents",
function(dir)
{
documentsDir = dir;
dir.listFiles(onsuccess, onerror);
},
function(e)
{
console.log("Error " + e.message);
},
"rw");
createDirectory
Creates a new directory.
Deprecated. Since 5.0
File createDirectory(DOMString dirPath);
Since: 1.0
A new directory will be created relative to the current directory that this operation is performed on. The implementation will attempt to create all necessary sub-directories specified in the dirPath, as well. The use of "." or ".." in path components is not supported.
This operation can only be performed on file handles that represent directories (that is, isDirectory == true).
If the directory is successfully created, it will be returned.
In case the directory cannot be created, an error must be thrown with the appropriate error type.
dirPath: Relative directory path and it only contains characters supported by the underlying filesystem.
Return value:
File: File handle of the new directory. The new File object has "rw" access rights, as it inherits this from the File object on which the createDirectory() method is called.
Exceptions:
WebAPIException
with error type IOError, if the dirPath already exists, if the file in which the createDirectory() method is invoked is a file (and not a directory).
with error type InvalidValuesError, if the dirPath does not contain a valid path.
with error type TypeMismatchError, if the input parameter is not compatible with the expected type.
with error type SecurityError, if the application does not have the privilege to call this method or the application does not have privilege to access the storage. For more information, see Storage privileges.
with error type UnknownError, if any other error occurs.
Code example:
var dir; /* Directory object obtained from filesystem API. */
var newDir = dir.createDirectory("newDir");
var anotherNewDir = dir.createDirectory("newDir1/subNewDir1");
createFile
Creates a empty new file in a specified location that is relative to the directory indicated by current File object's path attribute.
Deprecated. Since 5.0
File createFile(DOMString relativeFilePath);
Since: 1.0
The use of "." or ".." in path components is not supported. This operation can only be performed on file handlers that represent a directory (that is, isDirectory == true).
If the file is successfully created, a file handle must be returned by this method.
In case the file cannot be created, an error must be thrown with the appropriate error type.
relativeFilePath: New file path and it should only contain characters supported by the underlying filesystem.
Return value:
File: File handle for the new empty file. The new File object has "rw" access rights, as it inherits this from the File object on which the createFile() method is called.
Exceptions:
WebAPIException
with error type IOError, if relativeFilePath already exists, if the File in which the createFile() method is invoked is a file (not a directory).
with error type InvalidValuesError, if relativeFilePath contains an invalid value.
with error type TypeMismatchError, if the input parameter is not compatible with the expected type.
with error type SecurityError, if the application does not have the privilege to call this method or the application does not have privilege to access the storage. For more information, see Storage privileges.
with error type UnknownError, if any other error occurs.
Code example:
var newFile = dir.createFile("newFilePath");
resolve
Resolves an existing file or directory relative to the current directory this operation is performed on and returns a file handle for it.
Deprecated. Since 5.0
File resolve(DOMString filePath);
Since: 1.0
The filePath is not allowed to contain the "." or ".." directory entries inside its value.
This method attempts to asynchronously delete a directory or directory tree under the current directory.
If the recursive parameter is set to true, all the directories and files under the specified directory must be deleted. If the recursive parameter is set to false, the directory is only deleted if it is empty, otherwise an IOError error type will be passed in onerror().
If the deletion is performed successfully, the onsuccess() is invoked.
The ErrorCallback is launched with these error types:
InvalidValuesError - If any of the input parameters contains an invalid value.
NotFoundError -If the passed directory does not correspond to a valid directory.
IOError - If the File in which the delete method is invoked is a file (and not a directory), the directory is in use by another process or the directory is not empty and recursive argument is false.
This code is also used if a recursive deletion partially fails and any data deleted so far cannot be recovered. This may occur due to the lack of filesystem permissions or if any directories or files are already opened by other processes.
directoryPath: Full virtual path to the directory to delete (must be under the current one).
recursive: Flag indicating whether the deletion is recursive or not
When set to true recursive deletion is allowed. Also, this function deletes all data in all subdirectories and so needs to be used with caution.
onsuccess[optional][nullable]: Callback method to be invoked when a directory is successfully deleted.
onerror[optional][nullable]: Callback method to be invoked when an error has occurred.
Exceptions:
WebAPIException
with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.
with error type SecurityError, if the application does not have the privilege to call this method or the application does not have privilege to access the storage. For more information, see Storage privileges.
Code example:
var documentsDir;
function onsuccess(files)
{
for (var i = 0; i < files.length; i++)
{
if (files[i].isDirectory)
{
documentsDir.deleteDirectory(files[i].fullPath, false,
function()
{
console.log("Directory Deleted");
},
function(e)
{
console.log("Error " + e.message);
});
}
}
}
function onerror(error)
{
console.log(
"The error " + error.message + " occurred when listing the files in the selected folder");
}
tizen.filesystem.resolve("documents",
function(dir)
{
documentsDir = dir;
dir.listFiles(onsuccess, onerror);
},
function(e)
{
console.log("Error " + e.message);
},
"rw");
deleteFile
Deletes a specified file.
This function attempts to asynchronously delete a file under the current directory.
If the deletion is performed successfully, the onsuccess() is invoked.
The ErrorCallback is launched with these error types:
InvalidValuesError - If any of the input parameters contains an invalid value.
NotFoundError - If the file does not correspond to a valid file.
IOError - If the file in which the delete() method is invoked is a file (not a directory), the file is in use by another process, or there is no permission in the file system.
filePath: Full virtual path to the file to delete (must be under the current directory).
onsuccess[optional][nullable]: Callback method to be invoked when the file is successfully deleted.
onerror[optional][nullable]: Callback method to be invoked when an error has occurred.
Exceptions:
WebAPIException
with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.
with error type SecurityError, if the application does not have the privilege to call this method or the application does not have privilege to access the storage. For more information, see Storage privileges.
Code example:
var documentsDir;
function onsuccess(files)
{
for (var i = 0; i < files.length; i++)
{
if (!files[i].isDirectory)
{
documentsDir.deleteFile(files[i].fullPath,
function()
{
console.log("File Deleted");
},
function(e)
{
console.log("Error " + e.message);
});
}
}
}
function onerror(error)
{
console.log(
"The error " + error.message + " occurred when listing the files in the selected folder");
}
tizen.filesystem.resolve("documents",
function(dir)
{
documentsDir = dir;
dir.listFiles(onsuccess, onerror);
},
function(e)
{
console.log("Error " + e.message);
},
"rw");
2.6. FileFilter
The dictionary that defines attributes to filter the items returned by the listDirectory() method (or deprecated listFiles()).
dictionary FileFilter {
DOMString name;
boolean isFile;
boolean isDirectory;
Date startModified;
Date endModified;
Date startCreated;
Date endCreated;
};
Since: 1.0
When this dictionary is passed to a method, the result-set of the method will only contain file item entries that match the attribute values of the filter.
A file item only matches the FileFilter object if all of the defined filter's attribute values match all of the file item's attributes (only matching values other than undefined or null). This is similar to a SQL's "AND" operation.
An attribute of the file entry matches the FileFilter attribute value in accordance with the following rules:
For FileFilter attributes of type DOMString, an entry matches this value only if its corresponding attribute is an exact match. If the filter contains U+0025 "PERCENT SIGN" it is interpreted as a wildcard character and "%" matches any string of any length, including no length. If wildcards are used, the behavior is similar to the LIKE condition in SQL. To specify that a "PERCENT SIGN" character is to be considered literally instead of interpreting it as a wildcard, developers can escape it with the backslash character (). Please, remember that the backslash character has to be escaped itself, to not to be removed from the string - proper escaping of the "PERCENT SIGN" in JavaScript string requires preceding it with double backslash ("%"). The matching is not case sensitive, such as "FOO" matches a "foo" or an "f%" filter.
For File entry attributes of type Date, attributes start and end are included to allow filtering of File entries between two supplied dates. If either or both of these attributes are specified, the following rules apply:
A) If both start and end dates are specified (that is, other than null), a File entry matches the filter if its corresponding attribute is the same as either start or end or between the two supplied dates (that is, after start and before end).
B) If only the start attribute contains a value (other than null), a File entry matches the filter if its corresponding attribute is later than or equal to the start one.
C) If only the end date contains a value (other than null), a file matches the filter if its corresponding attribute is earlier than or equal to the end date.
Dictionary members
DOMString name
The File name attribute filter.
Files that have a name that corresponds with this attribute (either exactly or with the specified wildcards) match this filtering criteria.
Since: 1.0
boolean isFile
If true match only files. If false do not match files. May be undefined.
Since: 5.0
boolean isDirectory
If true match only directories, If false do not match directories. May be undefined.
Since: 5.0
Date startModified
The File modified attribute filter.
Files with modified date later than this attribute or equal to it match the filtering criteria.
Since: 1.0
Date endModified
The File modified attribute filter.
Files with modified date earlier than this attribute or equal to it match the filtering criteria.
Since: 1.0
Date startCreated
The File created attribute filter.
Files with created date later than this attribute or equal to it match the filtering criteria.
Since: 1.0
Date endCreated
The File created attribute filter.
Files with created date earlier than this attribute or equal to it match the filtering criteria.
Since: 1.0
2.7. FileStream
The FileStream interface represents a handle to a File opened for read and/or write operations. Read and write operations are performed relative to a position attribute, which is a pointer that represents the current position in the file.
A series of read/write methods are available that permit both binary and text to be processed.
Once a file stream is closed, any operation attempt made on this stream results in a standard JavaScript error.
The read/write operations in this interface do not throw any security exceptions as the access rights are expected to be granted through the initial resolve() method or through the openStream() method of the File interface. Therefore, all actions performed on a successfully resolved File and FileStream are expected to succeed. This avoids successive asynchronous calls and may potentially increase application for a user.
Attributes
readonly boolean eof
The flag indicating whether the current file pointer is at the end of the file.
Deprecated. Since 5.0
If set to true, this attribute indicates that the file pointer is at the end of the file.
If set to false, this attribute indicates that the file pointer is not at the end of the file and so it is anywhere within the file.
Since: 1.0
Code example:
if (stream.eof)
{
/* File has been read completely. */
}
long position
The flag indicating the stream position for reads/writes.
Deprecated. Since 5.0
The stream position is an offset of bytes from the start of the file stream. When invoking an operation that reads or writes from the stream, the operation will take place from the byte defined by this position attribute. If the read or write operation is successful, the position of the stream is advanced by the number of bytes read or written. If the read/write operation is not successful, the position of the stream is unchanged.
Since: 1.0
Code example:
console.log(stream.position); /* Displays current stream position. */
/* Alters current stream position to the begin of the file, */
/* like seek() in C. */
stream.position = 0;
readonly long bytesAvailable
The number of bytes that are available for reading from the stream.
Deprecated. Since 5.0
The number of bytes available for reading is the maximum amount of bytes that can be read in the next read operation. It corresponds to the number of bytes available after the file pointer denoted by the position attribute.
-1 if EOF is true.
Since: 1.0
Code example:
console.log(stream.bytesAvailable); /* Displays the available bytes to be read. */
Methods
close
Closes this FileStream.
Deprecated. Since 5.0
void close();
Since: 1.0
Flushes any pending buffered writes and closes the File. Always succeeds. Note that pending writes might not succeed.
stream.close(); /* Closes this stream, no subsequent access to stream allowed. */
read
Reads the specified number of characters from the position of the file pointer in a FileStream and returns the characters as a string. The resulting string length might be shorter than charCount if EOF is true.
octet[]: Result of read bytes as a byte (or number) array.
Exceptions:
WebAPIException
with error type IOError, if a read error occurs.
with error type TypeMismatchError, if the input parameter is not compatible with the expected type for that parameter.
with error type InvalidValuesError, if any of the input parameters contains an invalid value.
with error type SecurityError, if the application does not have the privilege to call this method. For more information, see Storage privileges.
Code example:
/* Reads up to 256 bytes from the stream. */
var raw = stream.readBytes(256);
for (var i = 0; i < raw.length; i++)
{
/* raw[i] contains the i-th byte of the current data chunk. */
}
readBase64
Reads the specified number of bytes from this FileStream, encoding the result in base64.
with error type IOError, if an error occurs during writeBase64.
with error type InvalidValuesError, if the input parameter contains an invalid value (e.g. the base64Data input parameter is not a valid Base64 sequence).
with error type SecurityError, if the application does not have the privilege to call this method. For more information, see Storage privileges.
Code example:
var base64 = input.readBase64(256);
/* Writes the base64 data read from input to output. */
output.writeBase64(base64);
2.8. FileSuccessCallback
The FileSuccessCallback interface defines file system success callback with a File object as input argument.
It is used in asynchronous operations, such as FileSystemManager.resolve(), copying, moving and deleting files.
Methods
onsuccess
Called when the asynchronous call completes successfully.
Deprecated. Since 5.0
void onsuccess(File file);
Since: 1.0
Parameters:
file: File resulting from the asynchronous call.
2.9. FileSystemStorageArraySuccessCallback
The FileSystemStorageArraySuccessCallback callback interface specifies a success callback with an array of FileSystemStorage objects as input argument.
This callback interface specifies a success callback with a function taking an array of strings as input argument. It is used in asynchronous operation FileSystemManager.listDirectory().
Methods
onsuccess
Called when the asynchronous call completes successfully.
void onsuccess(DOMString[] names, Path path);
Since: 5.0
Parameters:
names: File or directory names resulting from the asynchronous call.
path: Path to listed directory.
2.20. FileArraySuccessCallback
The FileArraySuccessCallback interface defines file system specific success callback for listing methods.
This callback interface specifies a success callback with a function taking an array of File objects as input argument. It is used in asynchronous methods, such as File.listFiles().
Methods
onsuccess
Called when the asynchronous call completes successfully.
Deprecated. Since 5.0
void onsuccess(File[] files);
Since: 1.0
Parameters:
files: Files resulting from the asynchronous call.
We use cookies to improve your experience on our website and to show you relevant
advertising. Manage you settings for our cookies below.
Essential Cookies
These cookies are essential as they enable you to move around the website. This
category cannot be disabled.
Company
Domain
Samsung Electronics
.samsungdeveloperconference.com
Analytical/Performance Cookies
These cookies collect information about how you use our website. for example which
pages you visit most often. All information these cookies collect is used to improve
how the website works.
Company
Domain
LinkedIn
.linkedin.com
Meta (formerly Facebook)
.samsungdeveloperconference.com
Google Inc.
.samsungdeveloperconference.com
Functionality Cookies
These cookies allow our website to remember choices you make (such as your user name, language or the region your are in) and
tailor the website to provide enhanced features and content for you.
Company
Domain
LinkedIn
.ads.linkedin.com, .linkedin.com
Advertising Cookies
These cookies gather information about your browser habits. They remember that
you've visited our website and share this information with other organizations such
as advertisers.
Company
Domain
LinkedIn
.linkedin.com
Meta (formerly Facebook)
.samsungdeveloperconference.com
Google Inc.
.samsungdeveloperconference.com
Preferences Submitted
You have successfully updated your cookie preferences.