Learning how to read and write to files, and move and copy files and directories, is a basic data management skill:
To open a file, use the openStream() method of the File interface.
The method returns a FileStream object, which is a handle to the opened file.
var documentsDir; var testFile = documentsDir.createFile("test.txt"); if (testFile != null) { testFile.openStream("w", onOpenSuccess, onOpenError, "UTF-8"); }
- Perform all actual operations, such as reading, writing, or closing, on the file through the FileStream object based on a position attribute, which represents the current position in the file:
function onOpenSuccess(fs) { /* Write HelloWorld to the file */ fs.write("HelloWorld"); /* Read the file content */ fs.read(testFile.fileSize); /* Close the file */ fs.close(); }
To copy a file or directory, use the copyTo() method. The following example copies the files to the images/backup/ directory. Since the third parameter is set to true, any existing files with the same name in the target directory are overwritten.
for (var i = 0; i < files.length; i++) { documentsDir.copyTo(files[i].fullPath, "images/backup/"+files[i].name, true, onsuccess, onerror); }
To move a file or directory, use the moveTo() method. The following example moves the files to the images/newFolder/ directory. Since the third parameter is set to false, no existing files with the same name in the target directory are overwritten.
for (var i = 0; i < files.length; i++) { documentsDir.moveTo(files[i].fullPath, "images/newFolder/"+files[i].name, false, onsuccess, onerror); }