3

I am trying to clear all the files in a folder using j2me. How do I do that?

gnat
  • 6,213
  • 108
  • 53
  • 73
JohnDoe4136
  • 529
  • 10
  • 32
  • 4
    @Mudassir - J2ME is **not** J2SE. Most of the J2SE library classes are missing ... including key classes that you'd use to do this in a J2SE application. – Stephen C Feb 09 '11 at 06:45

2 Answers2

9

Since you are using J2ME, the java.io.File class is not available to you.

So I am assuming that you are using the FileConnector Optional Package (FCOP).

Take a look at the javadocs for javax.microedition.io.file.FileConnection, and you should be able to figure out the details.

I'm not a J2ME expert, but I think that the code would look something like this:

FileConnection fconn = (FileConnection) Connector.open("file:///SomeDirectory");
Enumeration en = fconn.list();
while (en.hasMoreElements()) {
    String name = en.nextElement();
    FileConnection tmp = (FileConnection) Connector.open(
        "file:///SomeDirectory/" + name);
    tmp.delete();
    tmp.close();
}

Exception handling, proper resource handling (using finally) is left as an exercise for the reader :-)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Hey. Thanks. Just wondering if there is a sub-directory inside folder, do i use enumeration to look for files? – JohnDoe4136 Feb 09 '11 at 06:59
  • 1
    If there are potentially subdirectories, you will need to turn my code into a recursive method that empties subdirectories before deleting them. `FileConnection.delete()` is documented as throwing an exception if you try to delete a non-empty directory. – Stephen C Feb 09 '11 at 07:20
0

Use File.list() or File.listFiles() to get a list of the files. Then iterate the list and use File.delete() to delete them. The use File.delete() to delete the directory.

If you want to include subdirectories, do the previous code recursively, recursing as you hit each subdirectory, before you delete the directory.

Lawrence Dol
  • 63,018
  • 25
  • 139
  • 189