要求:需要向sd卡中的某个文件夹中的某个txt文件中写入一些用户信息
先不废话,直接上代码:
- <!DOCTYPE html>
- <html>
- <head>
- <title>FileWriter Example</title>
- <script type="text/javascript" charset="utf-8" src="../js/cordova-1.5.0.js"></script>
- <script type="text/javascript" charset="utf-8">
- //等待加载PhoneGap
- document.addEventListener("deviceready", onDeviceReady, false);
- // PhoneGap加载完毕
- function onDeviceReady() {
- window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
- }
- //获取newFile目录,如果不存在则创建该目录
- function gotFS(fileSystem) {
- newFile = fileSystem.root.getDirectory("newFile", {create : true,exclusive : false}, writerFile, fail);
- }
- //获取newFile目录下面的dataFile.txt文件,如果不存在则创建此文件
- function writerFile(newFile) {
- newFile.getFile("dataFile.txt", {create : true,exclusive : false}, gotFileEntry, fail);
- }
- function gotFileEntry(fileEntry) {
- fileEntry.createWriter(gotFileWriter, fail);
- }
- function gotFileWriter(writer) {
- writer.onwrite = function(evt) {
- alert("write success");
- };
- writer.write("some sample text");
- // 文件当前内容是"some sample text"
- writer.truncate(11);
- // 文件当前内容是"some sample"
- writer.seek(4);
- // 文件当前内容依然是"some sample",但是文件的指针位于"some"的"e"之后
- writer.write(" different text");
- // 文件的当前内容是"some different text"
- }
- function fail(error) {
- alert("Failed to retrieve file:" + error.code);
- }
- // 检索一个已存在的文件,如果该文件不存在时则创建该文件
- </script>
- </head>
- <body>
- <h1>Example</h1>
- <p>Write File</p>
- </body>
- </html>
在实现此功能时,是参考phonegap中国上面的API,不过如果完全按照API中介绍的去凑代码的话,则此功能还是比较难实现的。gotFS(fileSystem)与writerFile(newFile)中的两行代码不能写到一块,不然只执行第一行代码。譬如就不能像如下这种方式写:
- function gotFS(fileSystem) {
- newFile = fileSystem.root.getDirectory("newFile", {create : true,exclusive : false});
- newFile.getFile("dataFile.txt", {create : true,exclusive : false}, gotFileEntry, fail);
- }