3.6.Các thao tác trên FileConnection

Bạn có thể thực hiện một vài thao tác trên đối tượng FileConnection một khi việc kết nối file đã được hoàn tất.

  • Để kiểm tra xem một file hay thư mục tồn tại hay chưa, sử dụng phương thức exists().
  • Để kiểm tra xem một file hay thư mục ẩn hay chưa, sử dụng phương thức isHiddent().
  • Để tạo hay xóa một file hay thư mục, sử dụng các phương thức: create(), mkdir(), delete().
  • Để lấy danh sách các giá trị trong root, sử dụng phương thức listRoots() của lớp FileSystemRegistry.
  • Để list nội dung của thư mục mà đối tượng FileConnection trỏ tới, sử dụng phương thức list().
  • Gọi phương thức list(String filter, boolean includeHidden) để nhận về một danh sách các file hay thư mục được lọc(filter), trong đó:
    • filter: chuỗi ký tự để lọc; một ký tự “*” có thể được sử dụng làm ký tự đại diện để đại diện cho 0 hay nhiều lần xuất hiện của các ký tự.
    • includeHidden:  cho biết các file được đánh dấu là ẩn(hidden) nên được tính vào hay không trong danh sách các file và thư mục trả về.
    • Để write một file, bạn cần nhận một OutputStream từ đối tượng FileConnection trỏ đến file đang tồn tại:
...
  Enumeration e = fileConn.list();
  while (e.hasMoreElements()) {
  form.append(((String)e.nextElement()));
  }

OutputStream os=fileConn.openOutputStream();

  • Để read từ một file, bạn cần nhận một InputStream từ đối tượng FileConnection trỏ đến file đang tồn tại:

InputStream os = fileConn.openInputStream()

  • fileConn.canRead() và fileConn.Write() dùng để kiểm tra xem file/thư mục có thể đọc hoặc ghi không.
  • fileConn.directorySize(boolean includeSubDirs) được sử dụng để kiểm tra kích thước của các file lưu trong thư mục trong hệ thống file.
  • fileConn.fileSize() được sử dụng để xác định kích thước của một file. Bạn có thể thiết lập file của bạn là hidden/readable/wirteable bằng cách sử dụng phương thức fileConn.setHidden(boolean hidden), fileConn.setReadable(boolean readable), fileConn.setWriteable(boolean writeable).
  • fileConn.lastModified() được sử dụng để kiểm tra file được sửa đổi lần cuối cùng.

Ví dụ mẫu:

import java.io.IOException;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.Displayable;
import java.util.Enumeration;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.io.file.FileSystemRegistry;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.lcdui.ChoiceGroup;
public class FileMidletDemo extends MIDlet implements CommandListener{
            private Display display = null;
            private final Command CMD_EXIT = new Command("Exit",Command.EXIT,1);
            private final Command CMD_VIEW = new Command("View",Command.SCREEN,2);
            private final Command CMD_NEW  = new Command("New",Command.SCREEN,3);
            private final Command CMD_OK   = new Command("Ok",Command.OK,4);
            private final Command CMD_DELETE =  new Command("Delete",Command.SCREEN,5);
            private final String SEPERATOR  = "/";
            private Image image_dir = null;
            private Image image_file = null;
            private final char SEP ='/';
            private final String INIT_DIR="..";
            private String currentDir;
            private TextField textField=null;
            private ChoiceGroup choiceGroup=null;
            public FileMidletDemo() {
                        currentDir = SEPERATOR;
                        initRes();
                        display = Display.getDisplay(this);
                        initFileSys();
            }
            protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
            }
            protected void pauseApp() {
            }
            protected void startApp() throws MIDletStateChangeException {
            }
            private void createFile()
            {
                        Form form = new Form("New File");
                        textField = new TextField("Enter Name",null,256,TextField.ANY);
                        choiceGroup = new ChoiceGroup("Enter the file
                          Name",Choice.EXCLUSIVE, new String[]{"Regular File","Directory"},new Image[]{image_file,image_dir});
                        form.addCommand(CMD_EXIT);
                        form.addCommand(CMD_OK);
                        form.append(textField);
                        form.append(choiceGroup);
                        form.setCommandListener(this);
                        display.setCurrent(form);
            }
            private void executeMentionFile(String newFile,boolean isDir)
            {
                        try {
                                     FileConnection fileConn
                                  = (FileConnection)Connector.open("file:///"+currentDir+newFile);
                                     if(isDir)
                                                 fileConn.mkdir();
                                     else
                                                 fileConn.create();
                                     initFileSys();
                        } catch (IOException e) {
                                     e.printStackTrace();
                        }
            }
            private void showFile(String fileName)
            {
            }
            private void traversDir(String fileName)
            {
                        if (currentDir.equals(SEPERATOR)) {
                                     if (fileName.equals(INIT_DIR))
                                                 return;
                                     currentDir = fileName;
                        } else if (fileName.equals(INIT_DIR)) {
                                     int i = currentDir.lastIndexOf(SEP, currentDir.length() - 2);
                                     if (i != -1) {
                                                 currentDir = currentDir.substring(0, (i + 1));
                                     } else {
                                                 currentDir = SEPERATOR;
                                     }
                        } else {
                                     currentDir = currentDir + fileName;
                        }
                        initFileSys();
            }
            private void deleteFolder(String folder)
            {
                        try {
                                     FileConnection fileConn
                            =  (FileConnection)Connector.open("file://localhost/"+currentDir+folder);
                                     Enumeration e = fileConn.list("*",true);
                                     if(!e.hasMoreElements())
                                     {
                                                 fileConn.delete();
                                                 initFileSys();
                                     }
                                     else
                                     {
                                         Alert alert = new Alert("Error!!!","Cann't delete empty folder",null,AlertType.ERROR);
                                                 alert.setTimeout(Alert.FOREVER);
                                                 alert.addCommand(CMD_EXIT);
                                                 alert.setCommandListener(this);
                                                 display.setCurrent(alert);
                                     }
                        } catch (IOException e) {
                                     e.printStackTrace();
                        }
            }
            private void deleteFile(String file)
            {
                        try {
                                     FileConnection fileConn
                                 = (FileConnection)Connector.open("file://localhost/"+currentDir+file);
                                     fileConn.delete();
                        } catch (IOException e) {
                                     Alert alert =  new Alert("Error!",
                    "Can not access/delete file " + file + " in directory " + currentDir +
                    "\nException: " + e.getMessage(), null, AlertType.ERROR);
                                     alert.setTimeout(Alert.FOREVER);
                                     alert.addCommand(CMD_EXIT);
                                     alert.setCommandListener(this);
                                     display.setCurrent(alert);
                        }
            }
            private void delete(String file)
            {
                        if(!file.endsWith(INIT_DIR))
                        {
                                     if(file.charAt(file.length()-1)== SEP)
                                     {
                                                 deleteFolder(file);
                                     }
                                     else
                                     {
                                                 deleteFile(file);
                                     }
                        }
                        initFileSys();
            }
            private void initRes()
            {
              try {
                image_dir = Image.createImage(getClass().getResourceAsStream("/dir.png"));
                  image_file = Image.createImage(getClass().getResourceAsStream("/file.png"));
                } catch (IOException e) {
                                     e.printStackTrace();
                        }
            }
            private void initFileSys() {
                        List dirList = null;
                        Enumeration e = null;
                        FileConnection fileConn = null;
                        if (SEPERATOR.equals(currentDir)) {
                                     e = FileSystemRegistry.listRoots();
                                     dirList = new List(currentDir, Choice.IMPLICIT);
                        } else {
                                     try {
                                                 fileConn = (FileConnection) Connector.open("file://localhost/"
                                                                         + currentDir);
                                                 e = fileConn.list();
                                                 dirList = new List(currentDir, Choice.IMPLICIT);
                                                 dirList.append(INIT_DIR, image_dir);
                                     } catch (IOException e1) {
                                                 e1.printStackTrace();
                                     }
                        }
                        while (e.hasMoreElements()) {
                                     String element = (String) e.nextElement();
                                     if (element.charAt(element.length() - 1) == SEP)
                                                 dirList.append(element, image_dir);
                                     else
                                                 dirList.append(element, image_file);
                        }
                        if (fileConn != null)
                                     try {
                                                 fileConn.close();
                                     } catch (IOException e1) {
                                                 e1.printStackTrace();
                                     }
                                     dirList.addCommand(CMD_EXIT);
                                     dirList.addCommand(CMD_VIEW);
                                     dirList.addCommand(CMD_NEW);
                                     dirList.addCommand(CMD_DELETE);
                                     dirList.setCommandListener(this);
                                     display.setCurrent(dirList);
            }
            public void commandAction(Command cmd,Displayable dis)
            {
                        if(cmd == CMD_EXIT)
                        {
                                     try {
                                                 destroyApp(true);
                                                 notifyDestroyed();
                                     } catch (MIDletStateChangeException e) {
                                                 e.printStackTrace();
                                     }
                        }
                        else if(cmd == CMD_VIEW)
                        {
                                     List dirList =(List)dis;
                                     final String currentfile =
                                           dirList.getString(dirList.getSelectedIndex());
                                                 new Thread(new Runnable(){
                                                             public void run()
                                                             {
                                                                         if(currentfile.charAt(currentfile.length()- 1)==SEP
                                                                         ||currentfile.endsWith(INIT_DIR))
                                                                         {
                                                                                     traversDir(currentfile);
                                                                         }
                                                                         else
                                                                         {
                                                                                     showFile(currentfile);
                                                                         }
                                                             }
                                                 }).start();
                        }
                        else if(cmd == CMD_NEW)
                        {
                                     createFile();
                        }
                        else if (cmd == CMD_OK)
                        {
                                     final String newFile = textField.getString();
                                     if(newFile == null || newFile.equals(""))
                                     {
                                                 Alert alert  = new Alert("Error!!!","File name is empty....",
                                                                          null,AlertType.ERROR);
                                                 alert.setTimeout(Alert.FOREVER);
                                                 alert.addCommand(CMD_EXIT);
                                                 alert.setCommandListener(this);
                                                 display.setCurrent(alert);
                                     }
                                     else
                                     {
                                                 new Thread(new Runnable(){
                                                             public void run()
                                                             {
                                     executeMentionFile(newFile,(choiceGroup.getSelectedIndex())!=0);
                                                             }
                                                 }).start();
                                     }
                        }
                        else if(cmd == CMD_DELETE)
                        {
                                     List list = (List)dis;
                                     final String file = list.getString(list.getSelectedIndex());
                                     new Thread(new Runnable(){
                                                 public void run()
                                                 {
                                                             delete(file);
                                                 }
                                     }).start();
                        }
            }
}

Code

Các bài liên quan:
File Connection – JSR 75 (Phan 1)