利用PhoneGap向SD卡中写入文件

要求:需要向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);
	}
 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值