_________________________________________________________________________

||–|| File Handling Example ||–||

This example explains how we can use File handling API JSR 75 on J2me Handheld.I have used SonyEricsson Handset to test the Code. The following code does very simple job, It save the image in the File system of the phone. _________________________________________________________________________

Please click on more to see code ….

private void saveImageToFileSystem(){
new Thread(new NEWThread()).start();
System.out.println(” “+System.getProperty(”microedition.io.file.FileConnection.version”));
}
class ReadFromFileThread implements Runnable{
public ReadFromFileThread(){    }
public void run(){
FileConnection fileConnection2 = null;
InputStream is = null;
byte imageData[] = null;
try{
fileConnection2 = (FileConnection)Connector.open(”file:///c:/pictures/SampleImage_Three.jpg”, Connector.READ);
System.out.println(”FileConnection Created >>”+fileConnection2.exists());
if(fileConnection2.exists()){
System.out.println(”Going to read the file   “);
is = fileConnection2.openInputStream();

ByteArrayOutputStream baos = new ByteArrayOutputStream();
int ch;
while ((ch = is.read()) != -1)
baos.write(ch);

imageData = baos.toByteArray();
baos.close();

}
}catch(Exception e){

}

finally{
try{
is.close();
fileConnection2.close();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

try{
if(imageData!=null){

Image img = Image.createImage(imageData,0,imageData.length);

//Appending image on form
frm.append(img);
disp.setCurrent(frm);
}
}catch (Exception exp){
System.out.println(”Exception while creating an image >> “);
}
}
}

class NEWThread implements Runnable{
public NEWThread(){

}
public void run(){
FileConnection fileConnection = null;
OutputStream os = null;

try {
byte raw[] = null;

if(imgFrmNet != null){
raw = imgFrmNet;//getByteArray(imgFrmNet);
}

fileConnection = (FileConnection)Connector.open(”file:///c:/pictures/SampleImage_Three.jpg”, Connector.READ_WRITE);
System.out.println(”File Created >>  “+fileConnection.exists());

if(!fileConnection.exists()){
System.out.println(”Going to create file”);
fileConnection.create();
System.out.println(” file Created”);
os = fileConnection.openOutputStream();
os.write(raw);
System.out.println();
os.flush();
os.close();
}

Enumeration enumer = FileSystemRegistry.listRoots();
String dirString = (String)enumer.nextElement();
while(enumer.hasMoreElements()){
System.out.println((String)enumer.nextElement());
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
fileConnection.close();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}