Tuesday, March 15, 2011

Files and directories in AIR: Part 5

In this tutorial we'll find out how to copy and move files and directories using AIR.

Copying and moving files can be done using these functions: copyTo(), copyToAsync(), moveTo() and moveToAsync(). They are the same both for files and directories.

Copying and moving are very similar to each other - the file or directory simply gets moved to a new location, the only difference between them is that when a file is being copied, a new copy is created but the inital file is still there - in its initial place.

All these methods require just one parameter - a FileReference object that containst the new adress of the file. Keep in mind that the File class is a sub-class of FileReference, which means that we can also use a File object as the parameter.

Just like with the delete methods - there are both synchronous and asynchronous ways of moving and copying files and directories. Once again, if your file or directory is big - it is better to use async.

Here's an example of moving files:

import flash.filesystem.File;

var mySource:File = File.documentsDirectory.resolvePath("Temporary Folder");
var myDestination:File = File.desktopDirectory.resolvePath("Temporary Folder");

mySource.moveToAsync(myDestination);

Keep in mind that if there is no source file - the code will throw out an error. You can check if the file exists before moving it:

import flash.filesystem.File;

var mySource:File = File.documentsDirectory.resolvePath("Temporary Folder");
var myDestination:File = File.desktopDirectory.resolvePath("Temporary Folder");

if (mySource.exists)
{
mySource.moveToAsync(myDestination);
}

The methods also have an optional second parameter - a boolean, that defines whether we should allow AIR to overwrite any existing files if we need to when copying or moving our files or directories.

This way, if we encounter a Temporary Folder at the destination path, we will overwrite it when we move our directory:

import flash.filesystem.File;

var mySource:File = File.documentsDirectory.resolvePath("Temporary Folder");
var myDestination:File = File.desktopDirectory.resolvePath("Temporary Folder");

if (mySource.exists)
{
mySource.moveToAsync(myDestination, true);
}

That's all for now.

Thanks for reading!

Related:

Files and directories in AIR: Part 1
Files and directories in AIR: Part 2
Files and directories in AIR: Part 3
Files and directories in AIR: Part 4
Files and directories in AIR: Part 6
Files and directories in AIR: Part 7
Files and directories in AIR: Part 8
Files and directories in AIR: Part 9
Files and directories in AIR: Part 10
Files and directories in AIR: Part 11
Create a log application using XML and AIR: Part 1
Create a log application using XML and AIR: Part 2
Create a log application using XML and AIR: Part 3
Create a log application using XML and AIR: Part 4
Files and directories in AIR: Part 12

No comments:

Post a Comment