602 CHAPTER 16 Offline web applications
Creating and opening a file
To create a file, you must first have a DirectoryEntry object so you have an allocated place in
which to put the file. The FileSystem argument passed to successCallback includes a special
DirectoryEntry as a property named root, which points to the root of the file system reserved
specifically for the application (origin). Later in this lesson, you learn how to create a subdirec-
tory under root. For now, you create a new file in this location.
A DirectoryEntry object has a getFile method that can both create new files and read those
that already exist. The following are the parameters of the getFile method.
■■path ath to the file being requested. Both relative and absolute paths can be used.P
■■options llows for two flags, create and exclusive, that indicate how the file should A
be opened. If the file doesn’t exist, create must be set to true or an error will be
thrown. If both create and exclusive are set to true, an attempt will be made to create
the file but will throw an error if the file already exists.
■■successCallback he file is successfully created or opened, this callback will be If t
invoked with a FileEntry argument.
■■errorCallback If the request fails, this callback will be invoked and will include a
FileError argument.
The following example creates a new temporary file called “example.txt” in the root
directory.
window.requestFileSystem(TEMPORARY, 5 * 1024 * 1024, getFile, handleError);
function getFile(fileSystem) {
fileSystem.root.getFile("example.txt", { create: true }, fileOpened, handleError);
}
function fileOpened(fileEntry) {
alert("File opened!");
}
function handleError(error) {
alert(error.code);
}
Writing to a file
When you have access to a FileEntry object, you can create a FileWriter, which persists data
to the opened file. This is done by using its write method, which accepts a binary large object
(BLOB) data parameter.
In the following example, the fileOpened method in the previous example is modified to
create a new FileWriter and write a line of text to the opened document. Notice that in the
writeToFile method, you must assign the onwriteend and onerror callbacks before performing
the write action.