Friday, 13 July 2012

How to Read, Write and Copy file in Blackberry

It is very common feature in Blackberry to read/write/copy file programatically in BlackBerry.

Read file in the SDCard in the following way:

InputStream inputStream = null;
FileConnection fileConnection = (FileConnection) Connector.open( "file:///SDCard/testfile.txt");
if (fileConnection.exists())
{
inputStream = fconn.openInputStream();
}


ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
while (true) {
int bytesRead = inputStream.read( buffer, 0, BUFFER_SIZE );
if (bytesRead == -1)
break;
byteArrayOutputStream.write( buffer, 0, bytesRead );
}
byteArrayOutputStream.flush();
byte[] result = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
String resultString = new String(result);



Write/Save file in SDCard in the following way:

FileConnection fc = (FileConnection) Connector.open(System.getProperty("file:///SDCard/"+"fileName.txt"),Connector.READ_WRITE);
if(!fc.exists())
{
fc.create();
}
OutputStream os =fc.openOutputStream();
os.write("Test");
os.close();
fc.close()




Copy file in SDCard in the following way:

public static void copyFile(String srFile, String dtFile)
{
try
{
FileConnection f1;
FileConnection f2;

f1 = (FileConnection) Connector.open(srFile,Connector.READ_WRITE);
f2 = (FileConnection) Connector.open(dtFile,Connector.READ_WRITE);
if(!f2.exists()) // if file does not exists , create a new one
{
f2.create();
}
InputStream is = f1.openInputStream();
OutputStream os =f2.openOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf)) > 0)
{
os.write(buf, 0, len);
}
is.close();
os.close();
}
catch(IOException e)
{

}
}



Also check this link for more information about file path.

No comments:

Post a Comment