A Guide to Mobile and Web Technology(LAMP)

Posts tagged ‘operations’

How to do file operations in BlackBerry

Code to read data from a file

byte[] fulldata = null;
//Assign the name of the file to read the contents with full path
String filename = "/store/home/user/pictures/test.txt";
if (filename != null) {
    FileConnection file = (FileConnection) Connector.open("file://" +filename, Connector.READ);
    //Get the file size
    int fileSize = (int) file.fileSize();
    if (fileSize > 0) {
	fulldata = new byte[fileSize];
	InputStream input = file.openInputStream();    
	try{
	   input.read(fulldata);
	}
	catch(Exception sfg){
	    System.out.println(sfg.toString());
	}
	input.close();   
    }
    file.close();
}

Code to write data to a file

This function allows you to write byte array to the file specified.

//data -> byte array (Original data to be  written)
//filename -> name of the file in which those data has to be written

public static void writeFileData(byte[] data, String filename) {
        FileConnection file = null;
        OutputStream out = null;
        try {
            file = (FileConnection) Connector.open("file:///store/home/user/pictures/" + filename, Connector.READ_WRITE);
            if (file.exists())
                file.delete();
            
            file.create();
            out = file.openOutputStream();
            out.write(data);
        } 
        catch (IOException e) {
            System.out.println("Problem in writeFile : " + e.toString());
        } 
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (file != null && file.exists()) {
                    if (file.isOpen()) {          
                        file.close();
                    }
                }
            } 
            catch (IOException ioe) {
                System.out.println("Error while closing file: " + ioe);
            }
        }
    }//fn writeFileData

Code to delete a file


String filename = "/store/home/user/pictures/test.txt";
FileConnection file = null;
try {
    file = (FileConnection) Connector.open("file://" + filename, Connector.READ_WRITE);
} 
catch (IOException e) {
    System.out.println("Error in file connection : "+e.toString());
} 
finally {
    try {
	if (file != null && file.exists()) {                        
	    file.delete();
	}
    } 
    catch (IOException ioe) {
	System.out.println("Error in file deletion : "+ioe.toString());
    }
}
Follow

Get every new post delivered to your Inbox.

Join 38 other followers