javascript Phonegap - 在第一次加载时创建一个 .txt 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9462668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Phonegap - Creating a .txt file on first load
提问by Raj Labana
I am creating a phonegap app and need to create a new .txt file on first load. After this I need to check whether the file exists and then ignore the creation if that is the case, below is the general flow that I am after:
我正在创建一个 phonegap 应用程序,需要在第一次加载时创建一个新的 .txt 文件。在此之后,我需要检查文件是否存在,如果是这种情况,则忽略创建,以下是我所追求的一般流程:
1 - onDeviceReady - loading phoengap app 2 - Check is readme.txt exist (if yes load home page) 3 - Create a file readme.txt and add to www folder 4 - Continue loading homepage
1 - onDeviceReady - 加载 phoengap 应用程序 2 - 检查 readme.txt 是否存在(如果是,加载主页) 3 - 创建一个文件 readme.txt 并添加到 www 文件夹 4 - 继续加载主页
EDIT - Rather than the valid answer mentioned below I decided to use HTML5s local storage as this was simply 1 line of code.
编辑 - 而不是下面提到的有效答案,我决定使用 HTML5s 本地存储,因为这只是 1 行代码。
localStorage.setItem("name", "Email Supplied!");
and can be checked using this simple if statement
并且可以使用这个简单的 if 语句进行检查
if (localStorage.getItem("name") == "Email Supplied!")
{
// What you want to happen here
}
采纳答案by Titouan de Bailleul
You can take a look at the full example here:
您可以在此处查看完整示例:
http://docs.phonegap.com/en/1.4.1/phonegap_file_file.md.html#FileWriter
http://docs.phonegap.com/en/1.4.1/phonegap_file_file.md.html#FileWriter
This line create the file if it doesn't exist :
如果文件不存在,此行将创建文件:
fileSystem.root.getFile("readme.txt", {create: true, exclusive: false}, gotFileEntry, fail);
Supported Platforms
Android BlackBerry WebWorks (OS 5.0 and higher) iOS Windows Phone 7 ( Mango )
支持的平台
Android BlackBerry WebWorks(OS 5.0 及更高版本) iOS Windows Phone 7 (Mango)
I don't know about there others but in iOS, the document is created in /var/mobile/Application/YOU_APP/Documents
我不知道其他人,但在 iOS 中,文档是在 /var/mobile/Application/YOU_APP/Documents 中创建的
[CODE]
[代码]
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("readme.txt", {create: true}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
writer.onwrite = function(evt) {
console.log("write success");
};
writer.write("some sample text");
writer.abort();
// contents of file now 'some different text'
}
function fail(error) {
console.log("error : "+error.code);
}
</script>
Hope it helps
希望能帮助到你