如果我在移动设备上使用Phonegap Developer进行测试,则会给出以下代码,它会在我的Nexus 5设备的根目录中创建一个文件。
// create a file writer object
function CreateFileWriter()
{
// request the file system object
window.requestFileSystem( LocalFileSystem.PERSISTENT, 0, OnFileSystemSuccess,fail);
}
function OnFileSystemSuccess( pFileSystemObj )
{
console.log( pFileSystemObj.name );
console.log( pFileSystemObj.root.name );
pFileSystemObj.root.getFile( "file_name.txt", {create: true, exclusive: false}, OnFileGetSuccess, fail);
}
function OnFileGetSuccess( pFileEntryObj )
{
pFileEntryObj.createWriter( function(pWriterObj){
gWriterObj = pWriterObj;
}, fail );
}
function fail(evt)
{
console.log(evt.target.error.code);
}
但是,如果我部署应用程序并生成apk。安装在我的设备后。该文件不是以root身份创建的。
我已经在AndroidManifest.xml中获得了许可并添加了文件插件。另外,从gapdebug调试。它没有显示任何错误。我假设该文件是在其他地方创建的。但是我需要在sdcard或内存的根目录下写文件。
请帮助!
谢谢,
答案 0 :(得分:7)
写文件示例:
var fileName = 'myfile.txt'; // your file name
var data = '...'; // your data, could be useful JSON.stringify to convert an object to JSON string
window.resolveLocalFileSystemURL( cordova.file.externalRootDirectory, function( directoryEntry ) {
directoryEntry.getFile(fileName, { create: true }, function( fileEntry ) {
fileEntry.createWriter( function( fileWriter ) {
fileWriter.onwriteend = function( result ) {
console.log( 'done.' );
};
fileWriter.onerror = function( error ) {
console.log( error );
};
fileWriter.write( data );
}, function( error ) { console.log( error ); } );
}, function( error ) { console.log( error ); } );
}, function( error ) { console.log( error ); } );