如何从手机间隙中的目录中读取文件?

时间:2013-07-22 13:39:51

标签: cordova

您能告诉我如何从目录中读取文本文件吗?我需要从手机间隙中的文件夹中读取文件。我能够保存(写)。但问题是要读取文件吗? 你能告诉我如何阅读文件吗?

我可以保存文件。我需要的是阅读文件

代码低于

function readRtfFile(){
 try {
           window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
               function(fileSystem) {
                   fileSystem.root.getDirectory(CASENAME, { create: true, exclusive: false }, function(directoryEntry) {
                       console.log("log folder is created");
                       directoryEntry.getFile(DOCUMENT_NAME+".rtf", { create: true, exclusive: false }, function(fileEntry) {
                           fileEntry.createReader(function(writer) {
                               writer.readEntries(writer.length);


                           }, fail);
                       }, fail);
                   }, fail);
               },
               fail);
       }
       catch(e) {
           fail(e+"fail");
       }
}

2 个答案:

答案 0 :(得分:2)

试试这个 - 转到该目录并提供FileName -

window.resolveLocalFileSystemURL(DIR_PATH, 
    function(directoryEntry) {
        console.log('Directory Entry Log - ', directoryEntry);
        directoryEntry.getFile(fileName, { create: true, exclusive: false },

            function(fileEntry) {
                fileEntry.file(

                    function(file){
                        console.log('File Object Retrieved is - ', file);
                        var reader = new FileReader();
                        reader.onloadend = function(evt) {
                            console.log('File Content - ', reader.result);
                            if(evt.target.result) {
                                console.log('Result Event - ', evt);
                            } else {
                                console.log('Error. - ', evt);
                            }
                        };
                        reader.readAsText(file);
                    },
                    function(error) {
                        console.log('File Read cannot complete on File System - ', error);
                    }
                );
            }, function(error) {
                console.log('Reader cannot read from the File System - ', error);
            }
        );
    }, function(error) {
        console.log('Error - ', error);
    }
);

答案 1 :(得分:1)

来自PhoneGap的示例

http://docs.phonegap.com/en/2.5.0/cordova_file_file.md.html#DirectoryReader

function success(entries) {
    var i;
    for (i=0; i<entries.length; i++) {
        console.log(entries[i].name);
    }
}

function fail(error) {
    alert("Failed to list directory contents: " + error.code);
}

// Get a directory reader
var directoryReader = dirEntry.createReader();

// Get a list of all the entries in the directory
directoryReader.readEntries(success,fail);