I am looking for a quick and easy way to store variables in a text file, rather than use amfphp to connect to a database all I need to do is increment values every time a button is clicked .
Would be better if all the vars were in the same text file but if I have to have one per var that would be ok.
If your app is a desktop one, you can user AIR's File and FileStream classes in APPEND mode, like this:
// create the file reference
var file:File = File.documentsDirectory;
file = file.resolvePath("air_tests/saved_by_AIR.txt");
// create a stream object to read/write, and open in in APPEND mode
var stream:FileStream = new FileStream();
stream.open(file, FileMode.APPEND);
// add a new line to the text file
stream.writeUTFBytes( (new Date()).toString() + "\n" );
Desktop apps can use AIR's File and FileStream classes.
See protozoo's example for that.
However, if encryption is necessary, use the EncryptedLocalStore class.
var myVar:int=100; //This is what you'll increemnt.
var bytesToWrite:ByteArray=new ByteArray();
bytesToWrite.writeInt(myVar);
EncryptedLocalStore.setItem("myVar", bytesToWrite);
To retreive the value,
var storedValue:ByteArray = EncryptedLocalStore.getItem("myVar");
var readVar:int=storedValue.readInt();
You won't be able to save a file without a file dialog popping up (perhaps in AIR, but I haven't tested it), so this can quickly get annoying. If it's only for internal use - as in you don't need to access it outside of flash - then check out the SharedObject class instead: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/SharedObject.html
Works pretty much like a normal Object, it's just persisted over multiple plays
Related
I want to add my FileFilter in as3. Because there is the main problem of extension typing. I already use this option
(saveFile.save(bytes,_dbookNameFill+".doc"));
but I want to automatically generate this extension when I save my file any names. Please Help Me I am Mini Programmer.
var bytes:ByteArray = document.save(Method.LOCAL);
var saveFile:FileReference = new FileReference()
var _dbookNameFill:String =
QSTPreviwForStudentMC._bookNameMc.bookNtxt.text;
var fileFilter:FileFilter=new FileFilter("*.doc","*.text;*.RTF;");
saveFile.save(bytes,_dbookNameFill+".doc");
I'm afraid this won't work. Using AS3's FileFilter class you're just able to limit
what's being displayed on a file dialog you've opened using Filereference.browse().
FileReference.save() isn't affected by a FileFilter and as far as I know there is
no way to force a particular file extension - perhaps due to security reasons.
Having a few problems that after three days of googling and coding I am unable to find any suitable answers so, I'm hoping that someone with far more Flash AS3 knowledge than me can help. I have frame on the Maintimeline of a flash Movie which requests and loads PHP generated XML. The PHP file is passed three variables from Flash which are then used to populate certain parts of the MySQL query in the PHP file. It all works wonderfully and I can populate a myriad dynamic text fields via my loadXML function. here's my code:
var req:URLRequest=new URLRequest("http://example.com/returnusers.php");
req.method = URLRequestMethod.POST;
var phpVars:URLVariables = new URLVariables();
phpVars.Group = myVar1;
phpVars.Company = myVar2;
phpVars.startRow = myStartRow;
req.data = phpVars;
var xml:XMLList;
var xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, loadXML);
xmlLoader.load(req);
My problem is that I also have several buttons that, when clicked, will change the values of the myVar1, myVar2 and myStartRow. and thus change the parameters of the query in the PHP file. I would like to resend these to the same PHP file for an updated xml output and for my dynamic text fields to be updated with the new xml data.The only problem is is that I don't know how. As you can problably tell I'm no Tech Wizz but I'd really appreciate if someone out there could help... Thanks in advance
What you are trying to implement is a classic MVC design - in simple words you have a model (database + php) that is dynamic (changes during run time) and you want your view to change according to the changes made in the model (the view is binded to the model)
The solution requires some architectural work that is a bit advanced and will take some learning time , this is a good start : http://www.moock.org/lectures/mvc/
I have an app that retrieves XML From a server I run... Im trying to limit the calls to the server (if possible) to improve responsiveness of the app and decrease the likelihood that the user will get errors if the data stream doesnt make the trip successfully for whatever reason -- i get some intermittent network monitor errors, it could be due to some wifi channel conflicts I think I have, but its still is a potential weak point in the overall process and if I can work around that need to call to the server each time the user performs an 'action' within the app.
what I'd like to do is use the local storage on the device to (upon launch of the app) retrieve and save the XML data, then change my httpservice url the local file.
I have some code I used before to successfully write and read config settings to a local text file, so Im pretty sure this can be achieved, just not sure how exactly to go about it.
thanks for any light someone can shed on this or any code examples anyone can share.
Load it by default from the applicationStorageDirectory if it doesnt exist donwload and save the xml to the applicationStorageDirectory
to load:
var xmlFile:File = File.applicationStorageDirectory.resolvePath("data.xml");
if (xmlFile.exists)
{
var fileStream:FileStream = new FileStream();
fileStream.open(xmlFile, FileMode.READ);
var xml:XML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable));// you will want to declare outside this scope, its just for show
fileStream.close();
}else{
downloadAndSaveXML();// if it doesnt exist dowload it then save it and call load again!
}
to save:
//download .xml first and save in the onComplete handler, im calling the file "xml"
var file:File = File.applicationStorageDirectory.nativePath("data.xml");
var stream:FileStream = new FileStream();
stream.open(file, FileMode.WRITE);
stream.writeUTFBytes(xml.toXMLString());
stream.close();
get the idea?
You will also need this compiler argument so the HTTPService doesnt look online for the xml
-locale en_US -use-network=false
You could not bother with dowloading the file in the firstplace and just embed it in the Application
here a link to the topic
I know it is possible to open files with their default application using the openWithDefaultApplication method of the file class. However, when you try to open an un-associated file (perhaps a proprietary or custom extension) using this method, a runtime error is thrown.
Is there anyway to prompt the user to open a file with a particular application like Windows does with it's "Open with..." dialog?
If not using the AIR the framework, via the NativeProcessAPI?
SOLUTION - using Pixel Elephants answer below as a foundation:
var processInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
processInfo.workingDirectory = file.parent;
processInfo.executable = new File("C:\\WINDOWS\\system32\\cmd.exe");
var args:Vector.<String> = new Vector.<String>();
args.push("/c");
args.push(file.name);
processInfo.arguments = args;
var process:NativeProcess = new NativeProcess();
try
{
process.start(processInfo);
}
catch(e:Error)
{
//give up - open the folder
file.parent.openWithDefaultApplication();
}
The "Open with..." dialog on Windows shows whenever you try to launch an application that does not have an associate file type. Launch the application with NativeProcess.start() and Windows will take care of either opening it with the correct program, or presenting a selection screen if there is no file type associated.
Alternatively, depending on what you are trying to do, you may be interested in associating file types with your AIR application. For instance, you can associate PNG files with your AIR app so that they will by default open in your AIR app (e.g. double-clicking a PNG file will launch your app with an INVOKE event specifying the PNG file that was opened). See http://livedocs.adobe.com/flex/3/html/help.html?content=File_formats_1.html under "Declaring file type associations" for more information.
Of course, your AIR app may have no capabilities to handle opening whatever file you are trying to open and you want a different program to handle it, in which case you can just use the first method which will let the operating system take care of launching the application with the correct program.
EDIT :
I got confused as to what Native Process actually does. NativeProcess launches executables - NOT files, so the method above won't work.
Instead of trying to open the file directly with NativeProcess, try opening the program that you want to open the file with and pass the file in as an argument. For instance, if you want to open a PNG file with some special image program, you would do something like this:
var imageEditorProgram:File = new File("C:/Path/To/Program.exe");
var args:Vector.<String> = new Vector.<String>();
args.push("C:/Path/To/Image.png");
var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
nativeProcessStartupInfo.executable = imageEditorProgram;
nativeProcessStartupInfo.arguments = args;
var nativeProcess:NativeProcess = new NativeProcess();
nativeProcess.start(nativeProcessStartupInfo);
This should open the image editing program with the image file passed in.
However, the downside with this method is that you can't just let the operating system determine which program to open the file with. You should be able to open a file browse dialog and allow the user to select the program to open the file with (similar to how the operating system does it). So, hopefully the following would do what you want:
var file:File = File.userDirectory;
file.addEventListener(Event.SELECT, selectHandler);
file.browse();
private function selectHandler(e:Event):void{
file.removeEventListener(Event.SELECT, selectHandler);
var filePath:String= file.nativePath;
var imageEditorProgram:File = new File(filePath);
var args:Vector.<String> = new Vector.<String>();
args.push("C:/Path/To/Image.png");
var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
nativeProcessStartupInfo.executable = imageEditorProgram;
nativeProcessStartupInfo.arguments = args;
var nativeProcess:NativeProcess = new NativeProcess();
nativeProcess.start(nativeProcessStartupInfo);
}
I haven't tested the above code, but it should open a file browse dialog allowing the user to select a program to open the file with (perhaps you should add a FileFilter to restrict the user to selecting only .exe), and then launch that program using NativeProcess.
For user-friendliness you should consider saving user preferences for filetypes (so instead of forcing them to go through the file browser every time they want to open a PNG, just remember that they like to open PNG's with AwesomeImageEditor.exe).
How to put\save files into your application directory? (adobe air) (code example, please)
It's not recomended but it is possible. Construct your File reference like this:
var pathToFile:String = File.applicationDirectory.resolvePath('file.txt').nativePath;
var someFile:File = new File(pathToFile);
You can't write to your AIR app's Application Directory, it's not allowed. You can however write to a folder that your AIR app creates in the user's directory, called the Application Storage Directory. If you need config files and the like, that's probably the best place to put them. See 'applicationDirectory' in the docs link below:
http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/
#glendon
if you try to save directly to applicationDirectory it will indeed throw an error, but it seems you can move the file in the filesystem. i used the code below after yours:
var sourceFile:File = File.applicationStorageDirectory.resolvePath ("file.txt");
var pathToFile:String = File.applicationDirectory.resolvePath ('file.txt').nativePath;
var destination:File = new File (pathToFile);
sourceFile.moveTo (destination, true);
the reason why you 'shouldnt' use the application folder is because not all users have rights to save files in such folder, while everyone will in applicationStorageDirectory.
The accepted answer works!
But if I do this instead:
var vFile = File.applicationDirectory.resolvePath('file.txt');
var vStream = new FileStream();
vStream.open(vFile, FileMode.WRITE);
vStream.writeUTFBytes("Hello World");
vStream.close();
It will give SecurityError: fileWriteResource. However, if I use applicationStorageDirectory instead, the above code will work. It'll only NOT work if it's applicationDirectory. Moreover, Adobe's documentation also says that an AIR app cannot write to its applicationDirectory.
Now, I wonder if it's a bug on Adobe's part that they allow writing to the applicationDirectory using the way suggested by the accepted answer.
try this.
var objFile:File = new File(“file:///”+File.applicationDirectory.resolvePath(strFilePath).nativePath);
the output would be like this…
file:///c:\del\userConf.xml
This will work fine.
If you want write file into ApplicationDirectory, right?
Please don't forget for write for nativeprocess via powershell with registry key for your currect adobe application ( example: C:\Program Files (x86)\AirApp\AirApp.exe with RunAsAdmin )
nativeprocess saves new registry file
AirApp will restarts into RunASAdmin
AirApp can be writable possible with file :)
Don't worry!
I know that trick like sometimes application write frist via registry file and calls powershell by writing nativeprocess into registry file into registry structures.
Look like my suggestion from adobe system boards / forum was better than access problem with writing stream with file :)
I hope you because you know my nice trick with nativeprocess via powershell + regedit /s \AirApp.reg
and AirApp changes into administratived AirApp than it works fine with Administratived mode :)
Than your solution should write and you try - Make sure for your writing process by AirApp.
this function gives your current air application folder which bypasses the security problem:
function SWFName(): String {
var swfName: String;
var mySWF = new File(this.loaderInfo.url).nativePath;
swfName= this.loaderInfo.loaderURL;
swfName = swfName.slice(swfName.lastIndexOf("/") + 1); // Extract the filename from the url
swfName = new URLVariables("path=" + swfName).path; // this is a hack to decode URL-encoded values
mySWF = mySWF.replace(swfName, "");
return mySWF;
}