zoukankan      html  css  js  c++  java
  • jsr75 fileconnection 文件操作的方法.

    大致的需求就是, 浏览文件夹,以及文件,然后选取文件后,返回给调用窗口,进行进一步处理。

     使用方式:

       fileSelector= new FileSelector(this); //this 为MIDlet
       fileSelector.sender = invoker; //invoker 为自定义的Canvas
       Display.getDisplay(this).setCurrent(fileSelector);

    附带完整代码: 

    package BaseEngine;

    /**
     * <p>Title: FileSelector</p>
     * <p>Description: </p>
     * <p>Copyright: cnsoft  Copyright (c) 2009</p>
     * <p>Company: </p>
     * @author cnsoft#gmail.com
     * @version 1.0
     */
    /*
    * 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;

    import BaseEngine.xApplication;
    import BaseEngine.UI.xForm;


    public class FileSelector extends List implements CommandListener,FileSystemListener
    {
      private static String FILE_SEPARATOR ;
      private Command open = new Command("Open", Command.OK, 1);
      private Command back = new Command("Back", Command.BACK, 1);
      private String errorMsg = null;
      private Alert alert;
      private Vector rootsList = new Vector();
      private final static String upper_dir = "...";
      private FileConnection currentRoot = null;
      private static FileConnection fileConn2 = null;
      private static final int CHUNK_SIZE = 1024;

      public static ByteArrayInputStream  bis = null;
      public static xForm sender = null;

      FileSelector(xApplication xApplication) {
        super("File Browser", List.IMPLICIT);
        FILE_SEPARATOR = "/";
        //(System.getProperty("file.separator") != null) ? System.getProperty("file.separator") : "/";
        deleteAll();
        addCommand(open);
        addCommand(back);
        setSelectCommand(open);
        setCommandListener(this);
        FileSystemRegistry.addFileSystemListener(FileSelector.this);
        new Thread(new Runnable()
        {
          public void run() {
            execute();
            try {
              Thread.sleep(10);
            }
            catch (InterruptedException ex) {
            }
          }
        }).start();
      }

      public void execute() {
        //存储位置? Nokia机器上是啥呢?
        String initDir = "file:///root1/";//System.getProperty("fileconn.dir");
        //NokiaDevice  = "file:///C:/Data/Images/"
        String platform = System.getProperty("microedition.platform");
        if (platform.startsWith("Nokia"))
          initDir =  "file:///C:/Data/Images/";

        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("*.txt",false);
           while(listOfFiles.hasMoreElements())
           {
           String currentFile=(String) listOfFiles.nextElement();
           if(currentFile.endsWith(FILE_SEPARATOR))
           {
           //append(currentFile,null);
           }
           else
           {
           append(currentFile,null);
           }
           } */
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        catch (SecurityException e) {
           e.printStackTrace();
        }
        System.out.println("Display Root ok!");
      }

      private void displayAllRoots() {
        setTitle("[Roots]");
        deleteAll();
        Enumeration roots = rootsList.elements();
        while (roots.hasMoreElements()) {
          String root = (String) roots.nextElement();
          append(root.substring(1), null);
        }
        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 {
            //选择的是文件.检查是否是.txt 后缀的文件,
            //并尝试加载以后,如果失败,提示错误
            String url = currentRoot.getURL() + selectedFile;
            //设置回Canvas界面. 并传递数据 用于初始化.
            loadfiledata(url);
            //xForm. Invoker, 初始化新的卡片数据
            FlashGame flash = (FlashGame)sender;
            flash.LoadCard(flash.cards,(InputStream)bis);
            flash.resetGame();
            xApplication.instance.ReturnToCanvas();
          }
        }
      }

      public void loadfiledata(String url) {

      //FileConnection fileConn = null;
      try {
        fileConn2 = (FileConnection) Connector.open(url,
                                                   Connector.READ);
        fis = fileConn2.openInputStream();
        int overallSize = (int)fileConn2.fileSize();
        byte[] b = new byte[overallSize];
        int length = fis.read(b, 0, overallSize);
       // ByteArrayInputStream
        bis= new ByteArrayInputStream(b);

        fis.close();
        fileConn2.close();
       }
      catch (IOException ex) {
      }
      }

      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) {
          new Thread(new Runnable()
        {
          public void run()
          {
            openSelected();
          }}).start();
        }else
          if(c == back) {
            xApplication.instance.ReturnToCanvas();
          }
          ;// commandListener.commandAction(c, d);
      }

      public void rootChanged(int state, String rootNmae) {

      }

    }

  • 相关阅读:
    Linux:sudo,没有找到有效的 sudoers 资源。
    Python中关于CSV文件中的I/O
    Python数据处理进阶——pandas
    脚本的含义
    Common.Logging.dll----------配置方式,可选引用,用于日志输出
    Net作业调度
    MySQL版本介绍
    在 Windows 上安装Rabbit MQ 指南
    版本控制器
    C# 中的占位符本质
  • 原文地址:https://www.cnblogs.com/cnsoft/p/1406508.html
Copyright © 2011-2022 走看看