如何在iphone和android中的给定目录中创建文本文件

时间:2013-06-19 12:00:52

标签: jquery-mobile cordova

你可以告诉我在给定的目录中创建文本文件。我需要在该文本文件上写入。并从该文本文件中读取文本。 我可以使用此代码创建文件夹。但我需要在文件夹(newDir)中添加文本文件。

<!DOCTYPE html>
<html>
  <head>
    <title>Local File System Example</title>

    <script type="text/javascript" charset="utf-8" src="cordova-x.x.x.js"></script>
    <script type="text/javascript" charset="utf-8">

      // Wait for Cordova to load
      document.addEventListener("deviceready", onDeviceReady, false);

      // Cordova is ready
      function onDeviceReady() {
          window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, onFileSystemFail);
      }

      function onFileSystemSuccess(fileSystem) {
          console.log(fileSystem.name);
          var directoryEntry = fileSystem.root;
          directoryEntry.getDirectory("newDir", {create: true, exclusive: false}, onDirectorySuccess, onDirectoryFail)
      }

      function onDirectorySuccess(parent) {
          console.log(parent);
      }

      function onDirectoryFail(error) {
          alert("Unable to create new directory: " + error.code);
      }

      function onFileSystemFail(evt) {
          console.log(evt.target.error.code);
      }

    </script>
  </head>
  <body>
    <h1>Example</h1>
    <p>Local File System</p>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

Cordova File API包含您想要的所有信息。

以下代码创建一个目录,在目录中创建一个文件,并在文件中写入一些示例文本。

<script type="text/javascript" charset="utf-8">

    document.addEventListener("deviceready", onDeviceReady, false);

     // Cordova is ready
    function onDeviceReady() {
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
    }

    function gotFS(fileSystem) {
        // create dir
        fileSystem.root.getFile("newDir", {
            create: true,
            exclusive: false
        }, gotDirEntry, fail);
    }

    function () gotDirEntry(dirEntry) {
        // create file
        dirEntry.getFile("newFile.txt", {
            create: true,
            exclusive: false
        }, gotFileEntry, fail);
    }

    function gotFileEntry(fileEntry) {
        fileEntry.createWriter(gotFileWriter, fail);
    }

    function gotFileWriter(writer) {
        writer.onwrite = function (evt) {
            console.log("write completed");
        };
        writer.write("some sample text");
        writer.abort();
    }

    function fail(error) {
        console.log(error.code);
    }
</script>