How to copy/paste a file on SD Card

This is probably similar to the read/write topic, but I can't figure out how to copy a file from the SD Card, then paste it with a different name. Any suggestions, especially code :), would be greatly appreciated.

Thank you.

Trackback URL for this post:

http://blackberry.developercommunity.com/trackback/295

Here are the guts of how I solved it...

private boolean pasteFileAction()
{
// check to see if we are pasting in the same directory as the copied
// file
String pastefile = "";
if (_parentRoot.equals(_copiedfile.getPath()))
{
pastefile = "Copy of ";
}
pastefile += _copiedfile.getFileName();
FileConnection copiedFC = null;
FileConnection pasteFC = null;
OutputStream os = null;
try
{
copiedFC = (FileConnection)Connector.open(
MediaBrowser.getString(MediaBrowserResource.URL_PREFIX) +
_copiedfile.getPath() + _copiedfile.getFileName());
if (!copiedFC.exists())
{
Dialog.alert("ERROR - file does not exist?!?");
return false;
}
InputStream is= copiedFC.openInputStream();
//Open FileConnection to paste the file
pasteFC = (FileConnection)Connector.open(
MediaBrowser.getString(MediaBrowserResource.URL_PREFIX) +
_parentRoot + pastefile);
if (!pasteFC.exists())
{
pasteFC.create();
}
os = pasteFC.openOutputStream();
// Read in the bytes
// TODO: need to limit the size of bytes read based upon the free
// memory on device
long filesize = copiedFC.fileSize();
int size = (int)filesize;
byte[] b = new byte[size];
int sizeRead = size;
int offset = 0;
while ( size == sizeRead && filesize != 0)
{
sizeRead = is.read(b);
if (-1 == sizeRead)
{
throw new Exception("Recoverable Exception: Either no data in file or reached EOF.");
}
os.write(b, offset, sizeRead);
}
} catch (Exception ex) {
System.out.println(ex.toString());
} finally {
try
{
//flush the buffer
os.flush();
//close the connections
if (copiedFC != null)
{
copiedFC.close();
copiedFC = null;
}
if (pasteFC != null)
{
pasteFC.close();
pasteFC = null;
}
_copiedfile = null;
} catch (Exception ioex) {
}
}
return true;
}

 

There are many many improvements that could be made on the code, but the proof of concept is there.