Saturday, February 28, 2009

File Connection Using J2ME api JSR 75

Using the following code you can list the folders and files stored in the phone memory and the memory card.

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

/**
* @author test
*/
public class FileSelection extends MIDlet {
      private Display display;
      FileSelector fileSelector;
      public FileSelection() {
            display=Display.getDisplay(this);
      }
      public void startApp() {
            fileSelector=new FileSelector(this);
            display.setCurrent(fileSelector);
      }

      public void pauseApp() {
      }

      public void destroyApp(boolean unconditional) {
            notifyDestroyed();
      }
}



/*
* File Connection Using JSR 75
*/

import javax.microedition.lcdui.*;
import java.io.*;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import javax.microedition.io.*;
import javax.microedition.io.file.*;
import javax.microedition.io.file.FileConnection;
/**
*
* @author Administrator
*/
public class FileSelector extends List implements CommandListener,FileSystemListener {
      FileSelection fileSelection;
      private Display display;
      // define the file separator
      private final static String FILE_SEPARATOR =(System.getProperty("file.separator") != null) ? System.getProperty("file.separator") : "/";
      private Command open = new Command("Open", Command.OK, 1);
      private String errorMsg = null;
      private Alert alert;
      private Vector rootsList = new Vector();
      private final static String upper_dir = "...";
      private FileConnection currentRoot = null;
      private FileConnection fconn = null;
      private static final int CHUNK_SIZE = 1024;

      FileSelector(FileSelection fileSelection) {
            super("File Browser", List.IMPLICIT);
            this.fileSelection = fileSelection;
            deleteAll();
            addCommand(open);
            setSelectCommand(open);
            setCommandListener(this);
            FileSystemRegistry.addFileSystemListener(FileSelector.this);
            execute();
      }

      public void execute() {
            String initDir = System.getProperty("fileconn.dir");
            loadRoots();
            if (initDir != null) {
                  try {
                        currentRoot = (FileConnection) Connector.open(initDir, Connector.READ);
                        displayCurrentRoot();
                  } catch (Exception e) {
                        displayAllRoots();
                  }
            } else {
                  displayAllRoots();
            }
      }

      private void loadRoots() {
            if (!rootsList.isEmpty()) {
                  rootsList.removeAllElements();
            }
            try {
                  Enumeration roots = FileSystemRegistry.listRoots();
                  while (roots.hasMoreElements()) {
                        rootsList.addElement(FILE_SEPARATOR + (String) roots.nextElement());
                  }
            } catch (Throwable e) {
            }
      }

      private void displayCurrentRoot() {
            try {
                  setTitle(currentRoot.getURL());
                  deleteAll();
                  append(upper_dir, null);
                  Enumeration listOfDirs = currentRoot.list("*", false);
                  while (listOfDirs.hasMoreElements()) {
                        String currentDir = (String) listOfDirs.nextElement();
                        if (currentDir.endsWith(FILE_SEPARATOR)) {
                              append(currentDir, null);
                        } else {
                              append(currentDir, null);
                        }
                  }

                  /*Enumeration listOfFiles = currentRoot.list("*.png",false);
                  while(listOfFiles.hasMoreElements()) {
                        String currentFile=(String) listOfFiles.nextElement();
                        if(currentFile.endsWith(FILE_SEPARATOR)) {
                              append(currentFile,null);
                        }
                        else {
                              append(currentFile,null);
                        }
                  }*/
            } catch (IOException e) {
            } catch (SecurityException e) {
            }
      }

      private void displayAllRoots() {
            setTitle("[Roots]");
            deleteAll();
            Enumeration roots = rootsList.elements();
            while (roots.hasMoreElements()) {
                  String root = (String) roots.nextElement();
            }
            currentRoot = null;
      }

      private void openSelected() {
            int selectedIndex = getSelectedIndex();
            if (selectedIndex >= 0) {
                  String selectedFile = getString(selectedIndex);
                  if (selectedFile.endsWith(FILE_SEPARATOR)) {
                        try {
                              if (currentRoot == null) {
                                    currentRoot = (FileConnection) Connector.open("file:///" + selectedFile, Connector.READ);
                              } else {
                                    currentRoot.setFileConnection(selectedFile);
                              }
                              displayCurrentRoot();
                        } catch (IOException e) {
                              System.out.println(e.getMessage());
                        } catch (SecurityException e) {
                              System.out.println(e.getMessage());
                        }
                  } else if (selectedFile.equals(upper_dir)) {
                        if (rootsList.contains(currentRoot.getPath() + currentRoot.getName())) {
                              displayAllRoots();
                        } else {
                              try {
                                    currentRoot = (FileConnection) Connector.open("file://" + currentRoot.getPath(), Connector.READ);
                                    displayCurrentRoot();
                              } catch (IOException e) {
                                    System.out.println(e.getMessage());
                              }
                        }
                  } else {
                        String url = currentRoot.getURL() + selectedFile;
                        byteConvert(url, selectedFile);
            }
      }

      public void stop() {
            if (currentRoot != null) {
                  try {
                        currentRoot.close();
                  } catch (IOException e) {
                  }
            }
      }

      public void byteConvert(String url, String filename) {
            try {
                  FileConnection fileConn = (FileConnection) Connector.open(url, Connector.READ);
                  InputStream fis = fileConn.openInputStream();
                  long overallSize = fileConn.fileSize();
                  int length = 0;
                  byte[] filedata = new byte[0];
                  while (length < overallSize) {//converting the selected file to bytes
                        byte[] data = new byte[CHUNK_SIZE];
                        int readAmount = fis.read(data, 0, CHUNK_SIZE);
                        byte[] newFileData = new byte[filedata.length + CHUNK_SIZE];
                        System.arraycopy(filedata, 0, newFileData, 0, length);
                        System.arraycopy(data, 0, newFileData, length, readAmount);
                        filedata = newFileData;
                        length += readAmount;
                  }
                  fis.close();
                  fileConn.close();
                  //here u can write a code to connect with the server for sending the selected file
            } catch (Exception e) {
                  //showAlert(e.getMessage());
            } finally {
            }
      }

      public void commandAction(Command c, Displayable d) {
            if (c == open) {
                  openSelected();
            }
      }

      public void rootChanged(int state, String rootNmae) {
      }
}

19 comments:

Yolz said...

Hi, thank u for this..thanks a lot =D

But I got a problem, when I try to run the application, it will list only the "Folder", other file than "Folder" is not listed. Can u please help me with that? so that other files will also be listed

Another problem is when I want to see a content of one of the listed folders, it keeps give me errors like this:

java.lang.NullPointerException
at FileSelector.openSelected(+240)
at FileSelector.commandAction(+12)
at javax.microedition.lcdui.Display$DisplayAccessor.commandAction(+282)
at javax.microedition.lcdui.Display$DisplayManagerImpl.commandAction(+10)
at com.sun.midp.lcdui.DefaultEventHandler.commandEvent(+68)
at com.sun.midp.lcdui.AutomatedEventHandler.commandEvent(+47)
at com.sun.midp.lcdui.DefaultEventHandler$QueuedEventHandler.run(+250)


could you please help me with that???

Thank you so much..wait for your response

Ramesh.P said...

Hi yolz.. I checked my code with my mobile. Yes.. I got your first problem. It happens when we open the phone memory or memory card. It displays only the root folders like images,videos and themes, not displaying any files. But when we open any root folder like images,photos, it displaying all subfolders and files correctly.. my application opening the empty folder also... Im not getting your second problem.. Your error message says problem with DisplayManager, Event handler, etc.. Im not using these in my code.. Just try to copy this code separately and run the application without any modification. if it works fine then add in your code.

Thanks

Yolz said...

Hi, thanks a lot for this...
It works.. =D

Yolz said...

Hi, do u have any idea how to edit the file that we choose, and save the modification at memory card?

aswini said...

hi am ash

can anyone pls tell me how to store an captured image in to a folder as jpg file...

aswini said...

i tried the following code but its not working. if ( c == save)
{
FileConnection fconn =

(FileConnection)Connector.open("file:///C:/WTK2.5.1/apps/VideoMIDlet/res /mySnapshot.jpg");
if (!fconn.exists())
{
fconn.create(); // create the file if it doesn't exist
}
OutputStream out = fconn.openOutputStream();
//out.write(capturedImageByteArray);
out.write(raw);
fconn.close();
}

Ramesh.P said...

hi Ashwini..
Are you trying to store the image in mobile?
If yes, you give the phone memory file path..
i hope your code is correct.. problem with your url..
In nokia phones, phone memory is named as C and sdcard is named as E.

Distnie Zimmer said...

hey remesh!!!!
can u tell me the code to save a Image object as a image file in mobile device...

krishna said...

an object contains reference to memory location.

u can't simply save an object (Image/whatever) as an image(/whatever formats.).

U can save them.But, the saved content contains some rubbish(hashcode value) data[after saving the file, try reading it.u will know it in practical] and not the actual content.

krishna said...

if the object is initialised with some value, u can save the image .

check the sample code by "aswini" (also, referremesh's comments on it ). it does the work!

mani said...

hi ,
i want a sample j2me code for identifying an object from images if anyone know abt this please send me to manihuk@gmail.com

hungster said...

Well I get the same problem as yolz got from the beginning and the roots I see is my local drive roots. When I try to open c:\ which is on the list it gives me the same error as Yolz first comment.

Ramesh.P said...

Hi hungster
Where did u check this application?
in emulator? or real device?
Can u let me know?
Im getting your problen when i use netbeans emulator. It works fine in the real device. I checked with nokia 5300.

Thanks.

krishna Hidayat said...

Hi ramesh..
I've try to access a *.wav sounds in emulator..
I'm using netbeans 6.7 emulator..

but I was confuse, how to find the root folder in my simulator..
where the root folder is placed...

hm...
thanks.. :)

Peter Marcoen said...

Great code ! Thanks man ! Been searching for code that can locate my file and transfer it to bytes for a long time ..

Now I can finally upload pictures from my mobile to my server.

However .. With video it seems to have some difficulties.I'm using your code in combination with the HttpMultipartRequest code from nokia. It takes a long time to proces and get to my part of the script that uses HttpMultipartrequest. And even if it gets to the part where it asks for permission to use the network, the upload never reaches it's destination..

Any experience or remarks on this perhaps ?

Shyam said...

Hi,

Could you please send me a list of phoes on which this piece if code was tested?

I have tried it on my Nokia 3230 and my HTC Diamond..

The Nokia did not support the JSR75 and the HTC Diamond gave the version as 1.0...

However, the HTC Diamond, did not display the directories in the phone...

Awaiting your reply....

Thanks...

Shyam

Anonymous said...

Hi,

This code does not work on my emulator....

I get the value for selectedIndex as -1...

Also, you havent replied to my post yet Sir...

There is also a missing paranthesis in the code for the method openSelected()..

Awaiting your reply....

Thanks

Shyam..

Anonymous said...

Hi,
I have the same problem as some commentors. It can only list out the root directories inside my phone. When I want to view the folder contents. It wont show.

Can you tell me what I'm missing.
Thanks.

Anonymous said...

Can anybody help me?? I tried using the URL for creating a file with the path "file:///c:/tavo.txt", and it throws this exception

java.io.IOException: Can not create :
file:///c:/tavo.txt

Post a Comment