Phonegap Android write to sd card

Phonegap Android write to sd card

本文关键字:sd card to write Android Phonegap      更新时间:2023-09-26

如果我在手机中使用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。在我的设备中安装后。文件不是在根目录中创建的。

我已经在AndroidManifest.xml中授予了权限,并添加了文件插件。此外,从gapdebug调试。它没有显示任何错误。我认为该文件是在其他地方创建的。但我需要在SD卡或内部存储器的根上写文件。

请帮忙!

谢谢,

编写文件示例:

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 ); } );