FileWriter is an object that allows one to write a file.
The FileWriter
object is a way to write files from the devices file system. Users register their own event listeners to receive the writestart, progress, write, writeend, error and abort events.
A FileWriter is created for a single file. You can use it to write to a file multiple times. The FileWriter maintains the file‘s position and length attributes, so you can seek and write anywhere in the file. By default, the FileWriter writes to the beginning of the file (will overwrite existing data). Set the optional append boolean to true in the FileWriter’s constructor to begin writing to the end of the file.
function win(writer) { // fast forwards file pointer to end of file writer.seek(writer.length); }; var fail = function(evt) { console.log(error.code); }; entry.createWriter(win, fail);
function win(writer) { writer.truncate(10); }; var fail = function(evt) { console.log(error.code); }; entry.createWriter(win, fail);
function win(writer) { writer.onwrite = function(evt) { console.log("write success"); }; writer.write("some sample text"); }; var fail = function(evt) { console.log(error.code); }; entry.createWriter(win, fail);
function win(writer) { writer.onwrite = function(evt) { console.log("write success"); }; writer.seek(writer.length); writer.write("appended text"); }; var fail = function(evt) { console.log(error.code); }; entry.createWriter(win, fail);
function win(writer) { writer.onwrite = function(evt) { console.log("write success"); }; writer.write("some sample text"); writer.abort(); }; var fail = function(evt) { console.log(error.code); }; entry.createWriter(win, fail);
<!DOCTYPE html> <html> <head> <title>FileWriter Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.0.9.4.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail); } function gotFS(fileSystem) { fileSystem.root.getFile("readme.txt", null, gotFileEntry, fail); } function gotFileEntry(fileEntry) { fileEntry.createWriter(gotFileWriter, fail); } function gotFileWriter(writer) { writer.onwrite = function(evt) { console.log("write success"); }; writer.write("some sample text"); // contents of file now 'some sample text' writer.truncate(11); // contents of file now 'some sample' writer.seek(4); // contents of file still 'some sample' but file pointer is after the 'e' in 'some' writer.write(" different text"); // contents of file now 'some different text' } function fail(error) { console.log(error.code); } </script> </head> <body> <h1>Example</h1> <p>Write File</p> </body> </html>