⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fileselector.java

📁 实现图片的显示功能的J2ME程序
💻 JAVA
字号:
// Copyright 2004 Nokia Corporation.
//
// THIS SOURCE CODE IS PROVIDED 'AS IS', WITH NO WARRANTIES WHATSOEVER,
// EXPRESS OR IMPLIED, INCLUDING ANY WARRANTY OF MERCHANTABILITY, FITNESS
// FOR ANY PARTICULAR PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE
// OR TRADE PRACTICE, RELATING TO THE SOURCE CODE OR ANY WARRANTY OTHERWISE
// ARISING OUT OF ANY PROPOSAL, SPECIFICATION, OR SAMPLE AND WITH NO
// OBLIGATION OF NOKIA TO PROVIDE THE LICENSEE WITH ANY MAINTENANCE OR
// SUPPORT. FURTHERMORE, NOKIA MAKES NO WARRANTY THAT EXERCISE OF THE
// RIGHTS GRANTED HEREUNDER DOES NOT INFRINGE OR MAY NOT CAUSE INFRINGEMENT
// OF ANY PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OWNED OR CONTROLLED
// BY THIRD PARTIES
//
// Furthermore, information provided in this source code is preliminary,
// and may be changed substantially prior to final release. Nokia Corporation
// retains the right to make changes to this source code at
// any time, without notice. This source code is provided for informational
// purposes only.
//
// Nokia and Nokia Connecting People are registered trademarks of Nokia
// Corporation.
// Java and all Java-based marks are trademarks or registered trademarks of
// Sun Microsystems, Inc.
// Other product and company names mentioned herein may be trademarks or
// trade names of their respective owners.
//
// A non-exclusive, non-transferable, worldwide, limited license is hereby
// granted to the Licensee to download, print, reproduce and modify the
// source code. The licensee has the right to market, sell, distribute and
// make available the source code in original or modified form only when
// incorporated into the programs developed by the Licensee. No other
// license, express or implied, by estoppel or otherwise, to any other
// intellectual property rights is granted herein.
import java.io.*;
import java.util.*;
import javax.microedition.io.*;
import javax.microedition.io.file.*;
import javax.microedition.lcdui.*;

// Simple file selector class.
// It naviagtes the file system and shows images currently available
class FileSelector
  extends List
  implements CommandListener, FileSystemListener
{
  private final static Image ROOT_IMAGE =
    ImageViewerMIDlet.makeImage("/root.png");
  private final static Image FOLDER_IMAGE =
    ImageViewerMIDlet.makeImage("/folder.png");
  private final static Image FILE_IMAGE =
    ImageViewerMIDlet.makeImage("/file.png");
  private final OperationsQueue queue = new OperationsQueue();

  private final static String FILE_SEPARATOR =
    (System.getProperty("file.separator")!=null)?
      System.getProperty("file.separator"):
      "/";
  private final static String UPPER_DIR = "..";

  private final ImageViewerMIDlet midlet;
  private final Command openCommand =
    new Command("Open", Command.ITEM, 1);
  private final Command createDirCommand =
    new Command("Create new directory", Command.ITEM, 2);
  private final Command deleteCommand =
    new Command("Delete", Command.ITEM, 3);
  private final Command renameCommand =
    new Command("Rename", Command.ITEM, 4);
  private final Command exitCommand =
    new Command("Exit", Command.EXIT, 1);

  private final static int RENAME_OP = 0;
  private final static int MKDIR_OP = 1;
  private final static int INIT_OP = 2;
  private final static int OPEN_OP = 3;
  private final static int DELETE_OP = 4;

  private Vector rootsList = new Vector();
  // Stores the current root, if null we are showing all the roots
  private FileConnection currentRoot = null;


  FileSelector(ImageViewerMIDlet midlet)
  {
    super("Image Viewer", List.IMPLICIT);
    this.midlet = midlet;
    addCommand(openCommand);
    addCommand(createDirCommand);
    addCommand(deleteCommand);
    addCommand(renameCommand);
    addCommand(exitCommand);
    setSelectCommand(openCommand);
    setCommandListener(this);
    queue.enqueueOperation(new ImageViewerOperations(INIT_OP));
    FileSystemRegistry.addFileSystemListener(FileSelector.this);
  }


  void stop()
  {
    queue.abort();
    FileSystemRegistry.removeFileSystemListener(this);
  }


  void inputReceived(String input, int code)
  {
    switch (code)
    {
      case RENAME_OP:
        queue.enqueueOperation(new ImageViewerOperations(
          input,
          RENAME_OP));
        break;
      case MKDIR_OP:
        queue.enqueueOperation(new ImageViewerOperations(
          input,
          MKDIR_OP));
        break;
    }
  }


  public void commandAction(Command c, Displayable d)
  {
    if (c == openCommand)
    {
      queue.enqueueOperation(new ImageViewerOperations(OPEN_OP));
    }
    else if (c == renameCommand)
    {
      queue.enqueueOperation(new ImageViewerOperations(RENAME_OP));
    }
    else if (c == deleteCommand)
    {
      queue.enqueueOperation(new ImageViewerOperations(DELETE_OP));
    }
    else if (c == createDirCommand)
    {
      queue.enqueueOperation(new ImageViewerOperations(MKDIR_OP));
    }
    else if (c == exitCommand)
    {
      midlet.fileSelectorExit();
    }
  }


  // Listen for changes in the roots
  public void rootChanged(int state, String rootName)
  {
    queue.enqueueOperation(new ImageViewerOperations(INIT_OP));
  }


  private void displayAllRoots()
  {
    setTitle("Image Viewer - [Roots]");
    deleteAll();
    Enumeration roots = rootsList.elements();
    while (roots.hasMoreElements())
    {
      String root = (String) roots.nextElement();
      append(root.substring(1), ROOT_IMAGE);
    }
    currentRoot = null;
  }


  private void createNewDir()
  {
    if (currentRoot == null)
    {
      midlet.showMsg("Is not possible to create a new root");
    }
    else
    {
      midlet.requestInput("New dir name", "", MKDIR_OP);
    }
  }


  private void createNewDir(String newDirURL)
  {
    if (currentRoot != null)
    {
      try
      {
        FileConnection newDir =
          (FileConnection) Connector.open(
            currentRoot.getURL() + newDirURL,
            Connector.WRITE);
        newDir.mkdir();
      }
      catch (IOException e)
      {
        midlet.showError(e);
      }
      displayCurrentRoot();
    }
  }


  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) {
      midlet.showMsg(e.getMessage());
    }
  }


  private void deleteCurrent()
  {
    if (currentRoot == null)
    {
      midlet.showMsg("Is not possible to delete a root");
    }
    else
    {
      int selectedIndex = getSelectedIndex();
      if (selectedIndex >= 0)
      {
        String selectedFile = getString(selectedIndex);
        if (selectedFile.equals(UPPER_DIR))
        {
          midlet.showMsg("Is not possible to delete an upper dir");
        }
        else
        {
          try
          {
            FileConnection fileToDelete =
              (FileConnection) Connector.open(
                currentRoot.getURL() + selectedFile,
                Connector.WRITE);
            if (fileToDelete.exists())
            {
              fileToDelete.delete();
            }
            else
            {
              midlet.showMsg("File "
                + fileToDelete.getName() + " does not exists");
            }
          }
          catch (IOException e)
          {
            midlet.showError(e);
          }
          catch (SecurityException e)
          {
            midlet.showError(e);
          }
          displayCurrentRoot();
        }
      }
    }
  }


  private void renameCurrent()
  {
    if (currentRoot == null)
    {
      midlet.showMsg("Is not possible to rename a root");
    }
    else
    {
      int selectedIndex = getSelectedIndex();
      if (selectedIndex >= 0)
      {
        String selectedFile = getString(selectedIndex);
        if (selectedFile.equals(UPPER_DIR))
        {
          midlet.showMsg("Is not possible to rename the upper dir");
        }
        else
        {
          midlet.requestInput("New name", selectedFile, RENAME_OP);
        }
      }
    }
  }


  private void renameCurrent(String newName)
  {
    if (currentRoot == null)
    {
      midlet.showMsg("Is not possible to rename a root");
    }
    else
    {
      int selectedIndex = getSelectedIndex();
      if (selectedIndex >= 0)
      {
        String selectedFile = getString(selectedIndex);
        if (selectedFile.equals(UPPER_DIR))
        {
          midlet.showMsg("Is not possible to rename the upper dir");
        }
        else
        {
          try
          {
            FileConnection fileToRename =
              (FileConnection) Connector.open(
                currentRoot.getURL() + selectedFile,
                Connector.WRITE);
            if (fileToRename.exists())
            {
              fileToRename.rename(newName);
            }
            else
            {
              midlet.showMsg("File "
                + fileToRename.getName() + " does not exists");
            }
          }
          catch (IOException e)
          {
            midlet.showError(e);
          }
          catch (SecurityException e)
          {
            midlet.showError(e);
          }
          displayCurrentRoot();
        }
      }
    }
  }


  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)
        {
          midlet.showError(e);
        }
        catch (SecurityException e)
        {
          midlet.showError(e);
        }
      }
      else if (selectedFile.equals(UPPER_DIR))
      {
        if(rootsList.contains(currentRoot.getPath()
            +currentRoot.getName()))
        {
          displayAllRoots();
        }
        else
        {
          try
          {
            currentRoot.setFileConnection(UPPER_DIR);
            displayCurrentRoot();
          }
          catch (IOException e)
          {
            midlet.showError(e);
          }
        }
      }
      else
      {
        String url = currentRoot.getURL() + selectedFile;
        midlet.displayImage(url);
      }
    }
  }


  private void displayCurrentRoot()
  {
    try
    {
      setTitle("Image Viewer - [" + currentRoot.getURL() + "]");
      // open the root
      deleteAll();
      append(UPPER_DIR, FOLDER_IMAGE);
      // list all dirs
      Enumeration listOfDirs = currentRoot.list("*", false);
      while (listOfDirs.hasMoreElements())
      {
        String currentDir = (String) listOfDirs.nextElement();
        if (currentDir.endsWith(FILE_SEPARATOR))
        {
          append(currentDir, FOLDER_IMAGE);
        }
      }
      // list all png files and dont show hidden files
      Enumeration listOfFiles = currentRoot.list("*.png", false);
      while (listOfFiles.hasMoreElements())
      {
        String currentFile = (String) listOfFiles.nextElement();
        if (currentFile.endsWith(FILE_SEPARATOR))
        {
          append(currentFile, FOLDER_IMAGE);
        }
        else
        {
          append(currentFile, FILE_IMAGE);
        }
      }
      listOfFiles = currentRoot.list("*.jpg", false);
      while (listOfFiles.hasMoreElements())
      {
        String currentFile = (String) listOfFiles.nextElement();
        if (currentFile.endsWith(FILE_SEPARATOR))
        {
          append(currentFile, FOLDER_IMAGE);
        }
        else
        {
          append(currentFile, FILE_IMAGE);
        }
      }
    }
    catch (IOException e)
    {
      midlet.showError(e);
    }
    catch (SecurityException e)
    {
      midlet.showError(e);
    }
  }


  private class ImageViewerOperations implements Operation
  {
    private final String parameter;
    private final int operationCode;


    ImageViewerOperations(int operationCode)
    {
      this.parameter = null;
      this.operationCode = operationCode;
    }


    ImageViewerOperations(String parameter, int operationCode)
    {
      this.parameter = parameter;
      this.operationCode = operationCode;
    }


    public void execute()
    {
      switch (operationCode)
      {
        case INIT_OP:
          String initDir = System.getProperty("fileconn.dir.photos");
          loadRoots();
          if (initDir != null)
          {
            try
            {
              currentRoot =
                (FileConnection) Connector.open(
                  initDir,
                  Connector.READ);
              displayCurrentRoot();
            }
            catch (Exception e)
            {
              midlet.showError(e);
              displayAllRoots();
            }
          }
          else
          {
            displayAllRoots();
          }
          break;
        case OPEN_OP:
          openSelected();
          break;
        case DELETE_OP:
          deleteCurrent();
          break;
        case RENAME_OP:
          if (parameter != null)
          {
            renameCurrent(parameter);
          }
          else
          {
            renameCurrent();
          }
          break;
        case MKDIR_OP:
          if (parameter != null)
          {
            createNewDir(parameter);
          }
          else
          {
            createNewDir();
          }
      }
    }
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -