Saving and Loading files from an Android mobile Device using Flash Actionscript 3.0

前端 未结 1 399
無奈伤痛
無奈伤痛 2020-12-20 10:10

Im making a Test Maker App for both Desktop and Android. I was able to save and load in Desktop but failed on Android. I can ONLY save my file, but i cannot load my saved fi

相关标签:
1条回答
  • 2020-12-20 10:34

    I'm pretty sure you can't use a FileReference on mobile (though someone feel free to correct me if wrong).

    On mobile, you should use the File & FileStream classes for loading/saving local files.

    Here is an example, of using a compile time constant you could create (to determine if desktop or AIR) and loading appropriately into and out of a textfield called textfield:

    CONFIG::air {
        var file:File = File.applicationStorageDirectory.resolvePath("myFile.txt");
    
        if(file.exists){
            var stream:FileStream = new FileStream();
            stream.open(file, FileMode.READ);
    
            textfield.text = stream.readUTF(); //this may need to changed depending what kind of file data you're reading
    
            stream.close();
        }else{
            data = "default value"; //file doesn't exist yet
        }
    }
    
    CONFIG::desktop {
        //use your file reference code to populate the data variable
    }
    

    And to save: (assuming you have a textfield whose text you want to save)

    var fileStream:FileStream = new FileStream();
    fileStream.open(file, FileMode.WRITE);
    fileStream.writeUTF(textfield.text);
    fileStream.close();
    

    There are other save methods besides writeUTF (which is for plain text) writeObject is good for saving custom object when combined with flash.net.registerClassAlias

    File classes are in the flash.filesystem package

    EDIT

    Here is something you can try for letting the user pick the location on AIR.

    var file:File = File.applicationStorageDirectory;
    file.addEventListener(Event.SELECT, onFileSelected);
    file.browseForOpen("Open Your File", [new FileFilter("Text Files", "*.txt")]);
    
    function onFileSelected(e:Event):void {
        var stream:FileStream = new FileStream();
        stream.open(e.target as File, FileMode.READ);
    
        textField.text = stream.readUTF();
    }
    

    var saveFile:File = File.applicationStorageDirectory.resolvePath("myFile.txt");
    saveFile.addEventListener(Event.SELECT, onSaveSelect);
    saveFile.browseForSave("Save Your File");
    
    function onSaveSelect(e:Event):void {
        var file:File = e.target as File;
    
        var stream:FileStream = new FileStream();
        stream.open(file, FileMode.WRITE);
        stream.writeUTF(textField.text);
        stream.close();
    }
    
    0 讨论(0)
提交回复
热议问题