Back to Demos List

GSW Browser Write to File


This demonstration allows you to write to a file on the Android device as well as read from files on the device.

Steps:
1. Write text into the Input Text field.
2. Specify the name of the file in the File Name field





3. Read from file



About This Demo

This demo is using the cordova-plugin-file plugin. For more information click here:

	
/*
 *	cordova.file.dataDirectory							/data/data/com.gsw.connectbot
 *	cordova.file.applicationStorageDirectory			/data/data/com.gsw.connectbot/files
 *	cordova.file.cacheDirectory							/data/data/com.gsw.connectbot/cache
 *	cordova.file.externalApplicationStorageDirectory 	/sdcard/Android/data/com.gsw.connectbot
 *	cordova.file.externalDataDirectory					/sdcard/Android/data/com.gsw.connectbot/files
 *	cordova.file.externalCacheDirectory					/sdcard/Android/data/com.gsw.connectbot/cache
 */
var GSW = GSW || {};
GSW.Tests = GSW.Tests || {};


GSW.Tests.onDeviceReady = function() {
    console.log('Now running cordova-' + cordova.platformId + '@' + cordova.version);
    GSW.Tests.fsPath = cordova.file.externalDataDirectory;
    console.log("fspath set to " + GSW.Tests.fsPath);

    GSW.Tests.errorHandler = function(target, fileName, operation, e) {
        var msg = ''

        switch (e.code) {
            case FileError.QUOTA_EXCEEDED_ERR:
                msg = 'Storage quota exceeded'
                break
            case FileError.NOT_FOUND_ERR:
                msg = 'File not found'
                break
            case FileError.SECURITY_ERR:
                msg = 'Security error'
                break
            case FileError.INVALID_MODIFICATION_ERR:
                msg = 'Invalid modification'
                break
            case FileError.INVALID_STATE_ERR:
                msg = 'Invalid state'
                break
            default:
                msg = 'Unknown error ' + e.code
                break
        }

        var error_message = 'Error in ' + operation + ' (' + fileName + '): ' + msg;
        console.log(error_message)
        document.getElementById(target).innerHTML = error_message;
        if (target == "read_error")
            document.getElementById("data_from_file").innerHTML = "";
        if (target == "write_error")
            document.getElementById("success").innerHTML = "";
    }

    GSW.Tests.initFileRead = function() {
        var readFileName = document.getElementById('fileNameRead').value;
        let rFN = readFileName.concat(".json");
        GSW.Tests.readFromFile(rFN, function(data) {
            document.getElementById("data_from_file").innerHTML = data;
            document.getElementById("read_error").innerHTML = "";
        });

    }

    GSW.Tests.readFromFile = function(fileName, cb) {
        var pathToFile = GSW.Tests.fsPath + fileName
        window.resolveLocalFileSystemURL(
            //path
            pathToFile,
            //success handler
            function(fileEntry) {
                if (!fileEntry.isFile) {
                    GSW.Tests.errorHandler("read_error", fileName, "file check", new FileError(FileError.NOT_FOUND_ERR));
                    return;
                }
                fileEntry.file(function(file) {
                        var reader = new FileReader()
                        reader.onloadend = function(e) {
                            cb(JSON.parse(this.result))
                        }

                        reader.readAsText(file)
                    },

                    //error handler
                    GSW.Tests.errorHandler.bind(null, "read_error", fileName, "fileEntry.file"))
            },

            //error handler
            GSW.Tests.errorHandler.bind(null, "read_error", fileName, "resolveLocalFileSystemURL")
        )
    }


    GSW.Tests.writeToFile = function(fileName, data) {
        console.log("path in write: " + GSW.Tests.fsPath);
        data = JSON.stringify(data, null, '\t')
        window.resolveLocalFileSystemURL(
            GSW.Tests.fsPath,
            function(directoryEntry) {
                directoryEntry.getFile(
                    fileName, {
                        create: true
                    },

                    //success handler
                    function(fileEntry) {
                        fileEntry.createWriter(function(fileWriter) {
                                fileWriter.onwriteend = function(e) {
                                    // for real-world usage, you might consider passing a success callback
                                    console.log('Write of file "' + fileName + '"" completed.')
                                    document.getElementById("write_error").innerHTML = "";
                                    document.getElementById("success").innerHTML = "Write operation successful";
                                }

                                fileWriter.onerror = function(e) {
                                    // you could hook this up with our global error handler, or pass in an error callback
                                    console.log('Write failed: ' + e.toString())
                                    //GSW.Tests.errorHandler("write_error", fileName, "fileWriter", e);
                                }

                                var blob = new Blob([data], {
                                    type: 'text/plain'
                                })
                                fileWriter.write(blob)
                            },

                            //error handler
                            GSW.Tests.errorHandler.bind(null, "write_error", fileName, "createWriter"))
                    },

                    //error handler
                    GSW.Tests.errorHandler.bind(null, "write_error", fileName, "getFile")
                )
            },
            GSW.Tests.errorHandler.bind(null, "write_error", fileName, "resolveLocalFileSystemURL")
        )

    }


    GSW.Tests.startProcess = function() {
        // Cordova is now initialized Have fun!
        var text = document.getElementById('inputText').value;
        var file = document.getElementById('fileName').value;
        let finalFileName = file.concat(".json");
        //			var path = document.getElementById("location").value;
        //			console.log(path);
        //		GSW.Tests.fsPath = path;
        GSW.Tests.writeToFile(finalFileName, text);;
        console.log('Now running cordova-' + cordova.platformId + '@' + cordova.version);
    }
    document.getElementById("start").addEventListener("click", GSW.Tests.startProcess);
    document.getElementById("read").addEventListener("click", GSW.Tests.initFileRead);
}
document.addEventListener('deviceready', GSW.Tests.onDeviceReady, false);