0

你能告诉我在给定的目录中创建文本文件吗?我需要在那个文本文件上写。然后从那个文本文件中读取文本。我可以使用此代码创建文件夹。但我需要在文件夹中添加文本文件(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>
4

1 回答 1

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>
于 2013-06-19T13:47:16.917 回答