2013년 11월 12일 화요일

Writing and Reading to a File

Writing and Reading to a File

Key concepts
LocalFileSystem
Local file system에 접근 할 수 있게 해준다. 파일 접근 타입은 아래와 같이 2가지가 있으며 일반적으로 ‘PERSISTENT’로 접근한다.

LocalFileSystem.PERSISTENT
Data stored in a persistent file system should not be dledted by the UA, other than in response to removal API Call, without explicit authorization from the user.
LocalFilesystem.TEMPORARY
Data stored in a temporary file system may be deleted by the UA at its discretion, without application or user intervention.
fileSystem
File System을 표현한다. 일반적으로 아래와 같이 방식으로 사용되며, successCallback의 인자로 fileSystem 객체가  return 된다.

void requestFileSystem (
    short type, // LocalFileSystem.PERSISTENT or //LocalFileSystem.TEMPORARY
    long long size, //Size for TEMPORARY FS
    FileSystemCallback successCallback, //Success Callback
    optional ErrorCallback errorCallback  // Failure Callback
);
fileEntity
File 객체를 표현하며, 아래와 같은 방식으로 획득할 수 잇다.
window.resolveLocalFileSystemURL(
    “file:///sdcard/read-write.txt”,
    function(fileEntry){ },
    function(err){ }
);
directoryEntity
Directory 객체를 표현하며, 아래와 같은 방식으로 획득할 수 있다.
window.resolveLocalFileSystemURL(
    “file:///sdcard/mydir/”,
    function(directoryEntry){ },
    function(err){ }
);

Example Code

<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
<script type="text/javascript" src="phonegap-1.1.0.js">
</script>
<script type="text/javascript">
var filename = "read-write.txt";
var filePath = "file:///sdcard/read-write.txt";
var textarea = document.getElementById("textarea");
/** Called when phonegap javascript is loaded */
function onDeviceReady() {
var readButton = document.getElementById("read");
var writeButton = document.getElementById("write");
readButton.addEventListener("click", readFile, false);
writeButton.addEventListener("click", saveFile, false);
}
function readFile() {
//Contents shown below
}
function saveFile() {
//Contents shown below
}
/** Called when browser load this page*/
function init() {
document.addEventListener("deviceready", onDeviceReady, false);
}
</script>
</head>
<body onLoad="init()">
<h1>Read Write File</h1>
<table>
<tr>
<td colspan="2">/sdcard/read-write.txt</td>
</tr>
<tr>
<td colspan="2"><textarea id="textarea" rows="10" cols="30"> </textarea></td>
</tr>
www.it-ebooks.info CHAPTER 2: Getting Started with PhoneGap 65
<tr>
<td>
<button id="read">Read</button>
</td>
<td>
<button id="write">Write</button>
</td>
</tr>
</table>
</body>
</html>

ReadFile JavaScript
function readFile(){
window.resolveLocalFileSystemURI( //filename to be read
filePath, //success callback
function(fileEntry){
fileEntry.file(
function(file){
var fileReader = new FileReader();
fileReader.onloadend =
function(evt){
document.getElementById("textarea").value =
                                                                                               evt.target.result;
};
fileReader.readAsText(file);
},
function(error){
alert("Got error while reading "+filePath);
}
)
}, //error callback
function(error){
alert(filename + " not present, please add content and click Save first");
}
);
}

saveFile JavaScript
function saveFile() {
window.requestFileSystem(
LocalFileSystem.PERSISTENT, 0,
//Success Callback
function (fileSystem) {
var sdcardEntry = fileSystem.root;
sdcardEntry.getFile(filename, //Flag telling create file
{
create: true
},
//Success callbacks  
function (fileEntry) {
fileEntry.createWriter(
function (fileWriter) {
fileWriter.onwrite = function (evt) {
alert("Write was successful!");
document.getElementById("textarea").value = "";
};
fileWriter.write(document.getElementById("textarea").value);
},
//Error callback
function (error) {
alert("Failed to get a file writer for " + filename);
})
;
},
//Error Callback
function (error) {
alert("Got error while reading " + filename + " " + error);
}
);
},
function (error) {
alert("Got Error while gaining access to file system");
}
);
}

댓글 없음:

댓글 쓰기

블록체인 개요 및 오픈소스 동향

블록체인(block chain) 블록체인은 공공 거래장부이며 가상 화폐로 거래할때 발생할때 발생할 수 있는 해킹을 막는 기술. 분산 데이터베이스의 한 형태로, 지속적으로 성장하는 데이터 기록 리스트로서 분산 노드의 운영자에 의한 임의 조작이 불가...