利用PhoneGap向SD卡中写入文件

要求:需要向sd卡中的某个文件夹中的某个txt文件中写入一些用户信息

先不废话,直接上代码:

 

Html代码   收藏代码
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <title>FileWriter Example</title>  
  5.   
  6. <script type="text/javascript" charset="utf-8" src="../js/cordova-1.5.0.js"></script>  
  7. <script type="text/javascript" charset="utf-8">  
  8.     //等待加载PhoneGap  
  9.   
  10.     document.addEventListener("deviceready", onDeviceReady, false);  
  11.   
  12.     // PhoneGap加载完毕  
  13.   
  14.     function onDeviceReady() {  
  15.         window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);  
  16.     }  
  17.          //获取newFile目录,如果不存在则创建该目录  
  18.     function gotFS(fileSystem) {  
  19.         newFile = fileSystem.root.getDirectory("newFile", {create : true,exclusive : false}, writerFile, fail);       
  20.     }  
  21.     //获取newFile目录下面的dataFile.txt文件,如果不存在则创建此文件  
  22.     function writerFile(newFile) {  
  23.         newFile.getFile("dataFile.txt", {create : true,exclusive : false}, gotFileEntry, fail);  
  24.     }  
  25.       
  26.     function gotFileEntry(fileEntry) {  
  27.         fileEntry.createWriter(gotFileWriter, fail);  
  28.     }  
  29.   
  30.     function gotFileWriter(writer) {  
  31.         writer.onwrite = function(evt) {  
  32.             alert("write success");  
  33.         };  
  34.         writer.write("some sample text");  
  35.         // 文件当前内容是"some sample text"  
  36.         writer.truncate(11);  
  37.         // 文件当前内容是"some sample"   
  38.         writer.seek(4);  
  39.         // 文件当前内容依然是"some sample",但是文件的指针位于"some"的"e"之后  
  40.         writer.write(" different text");  
  41.         // 文件的当前内容是"some different text"  
  42.     }  
  43.   
  44.     function fail(error) {  
  45.         alert("Failed to retrieve file:" + error.code);  
  46.     }  
  47.   
  48.     // 检索一个已存在的文件,如果该文件不存在时则创建该文件  
  49. </script>  
  50. </head>  
  51. <body>  
  52.     <h1>Example</h1>  
  53.     <p>Write File</p>  
  54. </body>  
  55. </html>   

在实现此功能时,是参考phonegap中国上面的API,不过如果完全按照API中介绍的去凑代码的话,则此功能还是比较难实现的。gotFS(fileSystem)与writerFile(newFile)中的两行代码不能写到一块,不然只执行第一行代码。譬如就不能像如下这种方式写:

 

Html代码   收藏代码
  1. function gotFS(fileSystem) {  
  2.         newFile = fileSystem.root.getDirectory("newFile", {create : true,exclusive : false});         
  3.         newFile.getFile("dataFile.txt", {create : true,exclusive : false}, gotFileEntry, fail);  
  4.     }  
 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值