filePhoneGap向SD卡中写入文件

本文介绍了一个基于PhoneGap实现的文件读写示例。通过JavaScript API演示了如何创建目录和文件、写入内容及进行文件操作如truncate和seek等。
<span style="font-size:14px;"><!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></span>


注意:gotFS(fileSystem)与writerFile(newFile)中的两行代码不能写到一块,不然只执行第一行代码。譬如就不能像如下这种方式写:

<span style="font-size:14px;">function gotFS(fileSystem) {  
        <span style="color:#FF0000;">newFile</span> = <span style="color:#3333FF;">fileSystem</span>.root.getDirectory("newFile", {create : true,exclusive : false});         
        newFile.getFile("dataFile.txt", {create : true,exclusive : false}, gotFileEntry, fail);  
    }  </span>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值