Cordova 文件插件创建的文件位置在哪里?

Where is the location of file created by Cordova File Plugin?

我已经使用 Cordova File Plugin 在移动设备上创建文件。下面是创建文件的代码:

window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function (dir) {
   alert(cordova.file.dataDirectory);
   dir.getFile("log.txt", { create: true }, function (file) {
          alert("got the file: "+ file.name + ', ' + file.fullPath);
   });
});

当我在 android phone 上部署应用程序时,文件将成功创建,但我在我的设备上找不到创建的文件。

尽管 cordova.file.dataDirectory 指向我设备上的 file:///data/data/io.cordova.myappId/files/ 路径,io.cordova.myappId 文件夹不存在于 data>data 路径中,但存在于 Android>data 小路。顺便说一下,我检查了 storage>Android>data>io.Cordova.myappId>filesstorage>data>data 并且文件不存在。

这是因为:

创建的文件在另一个地方,我在哪里可以找到它?

因为它是私有的,我的文件管理器无权访问它,所以我如何更改权限设置以拥有 public 文件?

为什么我在我的设备上找不到文件?

文件已成功创建,但我无法在我的设备上找到该文件,因为我指示用于创建文件的 dataDirectory 路径是私有路径,而我的设备文件管理器无权访问到它(基于 this table)。实际上 dataDirectory 是一个 Internal Storage 选项。

Internal Storage: Store private data on the device memory.

You can save files directly on the device's internal storage. By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user). When the user uninstalls your application, these files are removed.(reference)

如何创建public文件?

因此,要在我的设备上创建一个我可以使用文件管理器访问它的文件,我必须使用 public 路径选项之一,例如:externalDataDirectory。之前我以为是用来把文件存到我的phone上没有的外置SD卡上,所以没测试。但是今天测试它,它在我的内部设备存储上创建了 Android/data/<app-id>/files 路径 public 中的文件,我可以使用设备文件管理器访问它。

实际上术语 internalexternal 对我有误导,而 external storage 可以是可移动存储介质(例如 SD 卡)或内部(non-removable) 存储(reference).

Reading/wiring Cordova 中的文件很痛苦。我写了一个脚本,使用 promises 使这更容易。

cordova-file-storage.js 添加到您的项目,然后执行以下操作:

// the object you want to save
var objectToSave = { firstName: 'John', lastName: 'Doherty' };

// the filename and extension you want to use
var filename = 'whatever.txt';

// the data to write (convert JSON object to a string)
var data = JSON.stringify(objectToSave);

// call write with params, .then executes with the filePath once complete
fileStorage.write(filename, data).then(function(filePath) {
     console.log(filePath);
})
.catch(function(err) {
     // this executes if something went wrong
     console.warn(err);
});

默认使用外部存储。要使用用户无法访问的沙盒存储,请添加 true 作为最后一个参数。