`
wuhua
  • 浏览: 2111577 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

Android 模拟J2me 通过连接框架

阅读更多

市场上J2ME的应用程序太多了。而Android。又是刚出产的东西,所以很多东西不完善等。虽然Android不支持J2me,但是Android提 供了Java开发接口,所以用这些APIs模拟一个J2ME也不是难事,今天我就试着模拟一个J2ME的JSR75的文件管理。
废话不说了,具体看下代码

这个是部分实现JSR75
 

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
 

public class FileConnectionImpl implements FileConnection {
    File iFile;
    final static int AVAILABLE_SIZE = 1024*1024*100;
    FileConnectionImpl(String sPath) throws IOException{
        iFile = new File(sPath);
        if(!iFile.exists())
            throw new IOException("File not exists!");
    }
    public long availableSize() {
        return AVAILABLE_SIZE;
    }

    public boolean canRead() {
        return iFile.canRead();
    }

    public boolean canWrite() {
        return iFile.canWrite();
    }

    public void create() throws IOException {
        iFile.createNewFile();

    }

    public void delete() throws IOException {
        iFile.delete();

    }

    public long directorySize(boolean _boolean) throws IOException {
       
        return 0;
    }

    public boolean exists() {
        return iFile.exists();
    }

    public long fileSize() throws IOException {
        return iFile.length();
    }

    public String getName() {
        return iFile.getName();
    }

    public String getPath() {
        return iFile.getPath();
    }

    public String getURL() {
        return ConnectionBaseInterface.FILE_PROTOCOL +this.getPath() + ConnectionBaseInterface.SEPARATOR
        + this.getName();
    }

    public boolean isDirectory() {
        return iFile.isDirectory();
    }

    public boolean isHidden() {
        return iFile.isHidden();
    }

    public boolean isOpen() {
        return iFile.isAbsolute();
    }

    public long lastModified() {
        return iFile.lastModified();
    }

    public Enumeration list() throws IOException {
        return new StringEnumeration(iFile.listFiles());
    }

    public Enumeration list(String string, boolean _boolean) throws IOException {
        // TODO Auto-generated method stub
        return null;
    }

    public void mkdir() throws IOException {
        if( !iFile.mkdir() )
            throw new IOException("mkdir faile!");

    }

    public DataInputStream openDataInputStream() throws IOException {
        DataInputStream sIS = new DataInputStream(new FileInputStream(iFile));
        return sIS;
    }

    public DataOutputStream openDataOutputStream() throws IOException {
        DataOutputStream sIS = new DataOutputStream(new FileOutputStream(iFile));
        return sIS;
    }

    public InputStream openInputStream() throws IOException {
        return new FileInputStream(iFile);
    }

    public OutputStream openOutputStream() throws IOException {
        return new FileOutputStream(iFile);
         
    }

    public OutputStream openOutputStream(long _long) throws IOException {
        // TODO Auto-generated method stub
        return null;
    }

    public void rename(String rename) throws IOException {
        iFile.renameTo(new File(rename));

    }

    public void setFileConnection(String string) throws IOException {
        // TODO Auto-generated method stub

    }

    public void setHidden(boolean aboolean) throws IOException {
        //iFile.se

    }

    public void setReadable(boolean aboolean) throws IOException {
        if(!aboolean)
            iFile.setReadOnly();
    }

    public void setWritable(boolean aboolean) throws IOException {
//        if(!aboolean)
//            iFile.

    }

    public long totalSize() {
       
        return iFile.length();
    }

    public void truncate(long _long) throws IOException {
         

    }

    public long usedSize() {
         
        return 0;
    }

    public void close() throws IOException {
        iFile = null;

    }

}

连接工厂实现
public class ConnectionBaseInterface {
    final static String FILE_PROTOCOL = "file://";
    final  static   String SEPARATOR = System.getProperty("file.separator");
     public final static Connection openPrim(String name, int mode, boolean timeouts)
     throws IOException{
         if(name.startsWith(FILE_PROTOCOL))
             return new FileConnectionImpl(name.substring(6, name.length()));
         return null;
             
     }
}

class StringEnumeration implements Enumeration{
    String[] iValues;
    boolean hasMore;
    int index;
    StringEnumeration(String[] aStrings){
        iValues = aStrings;
        if(iValues != null && iValues.length>1)
            hasMore = true;
    }
    StringEnumeration(File[] aFiles){
        if(aFiles == null)
            return;
        iValues = new String[aFiles.length];
         int i=0;
        for (File file : aFiles){
            iValues = file.getPath();
            i++;
        }
        //iValues = aStrings;
        if(iValues != null && iValues.length>1)
            hasMore = true;
    }
    public boolean hasMoreElements() {
         
        return hasMore;
    }

    public Object nextElement() {
        if(iValues == null)
            return null;
        String value;
        if(index >= 0 && index<iValues.length){
            if(index == iValues.length)
                hasMore = false;
            value =    iValues[index];
            index++;
            return value;
        }else{
            hasMore = false;
            return null;
        }
           
         
    }
   
}


系统工厂实现

/*
 *  
 *
 * Copyright  1990-2007 Sun Microsystems, Inc. All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version
 * 2 only, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License version 2 for more details (a copy is
 * included at /legal/license.txt).
 *
 * You should have received a copy of the GNU General Public License
 * version 2 along with this work; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
 * Clara, CA 95054 or visit www.sun.com if you need additional
 * information or have any questions.
 */



import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

 

/**
 * This class is a placeholder for the static methods that are used
 * for creating all the Connection objects.
 * <p>
 * The creation of Connections is performed dynamically by looking
 * up a protocol implementation class whose name is formed from the
 * platform name (read from a system property) and the protocol name
 * of the requested connection (extracted from the parameter string
 * supplied by the application programmer.)
 *
 * The parameter string that describes the target should conform
 * to the URL format as described in RFC 2396.
 * This takes the general form:
 * <p>
 * <code>{scheme}:[{target}][{parms}]</code>
 * <p>
 * where <code>{scheme}</code> is the name of a protocol such as
 * <i>http</i>}.
 * <p>
 * The <code>{target}</code> is normally some kind of network
 * address.
 * <p>
 * Any <code>{parms}</code> are formed as a series of equates
 * of the form ";x=y".  Example: ";type=a".
 * <p>
 * An optional second parameter may be specified to the open
 * function. This is a mode flag that indicates to the protocol
 * handler the intentions of the calling code. The options here
 * specify if the connection is going to be read (READ), written
 * (WRITE), or both (READ_WRITE). The validity of these flag
 * settings is protocol dependent. For instance, a connection
 * for a printer would not allow read access, and would throw
 * an IllegalArgumentException. If the mode parameter is not
 * specified, READ_WRITE is used by default.
 * <p>
 * An optional third parameter is a boolean flag that indicates
 * if the calling code can handle timeout exceptions. If this
 * flag is set, the protocol implementation may throw an
 * InterruptedIOException when it detects a timeout condition.
 * This flag is only a hint to the protocol handler, and it
 * does not guarantee that such exceptions will actually be thrown.
 * If this parameter is not set, no timeout exceptions will be
 * thrown.
 * <p>
 * Because connections are frequently opened just to gain access
 * to a specific input or output stream, four convenience
 * functions are provided for this purpose.
 *
 * See also: {@link DatagramConnection DatagramConnection}
 * for information relating to datagram addressing
 *
 * @version 1.1 1/7/2000
 * @version 1.2 12/8/2000 (comments revised)
 */

public class Connector {

/*
 * Implementation note: The open parameter is used for dynamically
 * constructing a class name in the form:
 * <p>
 * <code>com.sun.cldc.io.{platform}.{protocol}.Protocol</code>
 * <p>
 * The system property "microedition.protocolpath" can be used to
 * change the root of the class space that is used for looking
 * up the protocol implementation classes.
 * <p>
 * The protocol name is derived from the parameter string
 * describing the target of the connection. This takes the from:
 * <p>
 * <code> {protocol}:[{target}][ {parms}] </code>
 * <p>
 * The protocol name is used for dynamically finding the
 * appropriate protocol implementation class.  This information
 * is stripped from the target name that is given as a parameter
 * to the open() method.
 */

    /**
     * Access mode READ.
     */
    public final static int READ  = 1;

    /**
     * Access mode WRITE.
     */
    public final static int WRITE = 2;

    /**
     * Access mode READ_WRITE.
     */
    public final static int READ_WRITE = (READ|WRITE);

    /**
     * The platform name.
     */
    private static String platform;

    /**
     * The root of the classes.
     */
    private static String classRoot;

    /**
     * Class initializer.
     */
    static {
        /* Set up the platform name */
        platform = System.getProperty("microedition.platform");
        if (platform == null) {
            platform = "j2me";
        }

        /* See if there is an alternate protocol class root path */
        classRoot = System.getProperty("javax.microedition.io.Connector.protocolpath");
        if (classRoot == null) {
            classRoot = "com.sun.cldc.io";
        }
    }

    /**
     * Prevent instantiation of this class.
     */
    private Connector(){}

    /**
     * Create and open a Connection.
     *
     * @param name             The URL for the connection.
     * @return                 A new Connection object.
     *
     * @exception IllegalArgumentException If a parameter is invalid.
     * @exception ConnectionNotFoundException If the requested connection
     *   cannot be make, or the protocol type does not exist.
     * @exception IOException  If some other kind of I/O error occurs.
     */
    public static Connection open(String name) throws IOException {
        return open(name, READ_WRITE);
    }

    /**
     * Create and open a Connection.
     *
     * @param name             The URL for the connection.
     * @param mode             The access mode.
     * @return                 A new Connection object.
     *
     * @exception IllegalArgumentException If a parameter is invalid.
     * @exception ConnectionNotFoundException If the requested connection
     *   cannot be make, or the protocol type does not exist.
     * @exception IOException  If some other kind of I/O error occurs.
     */
    public static Connection open(String name, int mode)
        throws IOException {

        return open(name, mode, false);
    }

    /**
     * Create and open a Connection.
     *
     * @param name             The URL for the connection
     * @param mode             The access mode
     * @param timeouts         A flag to indicate that the caller
     *                         wants timeout exceptions
     * @return                 A new Connection object
     *
     * @exception IllegalArgumentException If a parameter is invalid.
     * @exception ConnectionNotFoundException if the requested connection
     * cannot be make, or the protocol type does not exist.
     * @exception IOException  If some other kind of I/O error occurs.
     */
    public static Connection open(String name, int mode, boolean timeouts)
        throws IOException {
        try {
            return openPrim(name, mode, timeouts);
        } catch(ClassNotFoundException x ) {
        }

        throw new ConnectionNotFoundException( "The requested protocol does not exist "+name);
    }

    /**
     * Create and open a Connection.
     *
     * @param string           The URL for the connection
     * @param mode             The access mode
     * @param timeouts         A flag to indicate that the caller
     *                         wants timeout exceptions
     * @return                 A new Connection object
     *
     * @exception ClassNotFoundException  If the protocol cannot be found.
     * @exception IllegalArgumentException If a parameter is invalid.
     * @exception ConnectionNotFoundException If the connection cannot
     *                                        be found.
     * @exception IOException If some other kind of I/O error occurs.
     * @exception IllegalArgumentException If a parameter is invalid.
     */
    private static Connection openPrim(String name, int mode,
                                       boolean timeouts)
        throws IOException, ClassNotFoundException {

        /* Test for null argument */
        if (name == null) {
            throw new IllegalArgumentException( "Null URL");
        }

        /* Look for : as in "http:", "file:", or whatever */
        int colon = name.indexOf(':');

        /* Test for null argument */
        if (colon < 1) {
            throw new IllegalArgumentException("no ':' in URL"
            );
        }

//        try {
            String protocol;

            /* Strip off the protocol name */
            protocol = name.substring(0, colon);

            /* sanity check the protocol name */
            char[] chars = protocol.toCharArray();
            for (int i = 0; i < chars.length; ++i) {
                char c = chars;
                /* only allow characters that are valid in RFC 2396
                   alpha *( alpha | digit | "+" | "-" | "." )
                */
                if ( ('A' <= c && c <= 'Z') ||
                     ('a' <= c && c <= 'z') ||
                     ( (i > 0) && (
                         ('0' <= c && c <= '9') ||
                         c == '+' ||
                         c == '-' ||
                         c == '.'))) {
                    continue;
                }
                throw new IllegalArgumentException("Invalid protocol name");
            }

            /* Strip the protocol name from the rest of the string */
            name = name.substring(colon+1);

            /* Use the platform and protocol names to look up */
            /* a class to implement the connection */
//            Class clazz =
//                Class.forName(classRoot +
//                              "." + platform +
//                              "." + protocol + ".Protocol");
//
//            /* Construct a new instance */
//            ConnectionBaseInterface uc =
//                (ConnectionBaseInterface)clazz.newInstance();

            /* Open the connection, and return it */
            return ConnectionBaseInterface.openPrim(name, mode, timeouts);

        }
//        catch (ClassCastException x) {
//            throw new IOException( x.toString()
//
//            );
//        }


    /**
     * Create and open a connection input stream.
     *
     * @param  name            The URL for the connection.
     * @return                 A DataInputStream.
     *
     * @exception IllegalArgumentException If a parameter is invalid.
     * @exception ConnectionNotFoundException If the connection cannot
     *                                        be found.
     * @exception IOException  If some other kind of I/O error occurs.
     */
    public static DataInputStream openDataInputStream(String name)
        throws IOException {

        InputConnection con = null;
        try {
            con = (InputConnection)Connector.open(name, Connector.READ);
        } catch (ClassCastException e) {
            throw new IOException(
/* #ifdef VERBOSE_EXCEPTIONS */
/// skipped                       e.toString()
/* #endif */
            );
        }

        try {
            return con.openDataInputStream();
        } finally {
            con.close();
        }
    }

    /**
     * Create and open a connection output stream.
     *
     * @param  name            The URL for the connection.
     * @return                 A DataOutputStream.
     *
     * @exception IllegalArgumentException If a parameter is invalid.
     * @exception ConnectionNotFoundException If the connection cannot
     *                                        be found.
     * @exception IOException  If some other kind of I/O error occurs.
     */
    public static DataOutputStream openDataOutputStream(String name)
        throws IOException {

        OutputConnection con = null;
        try {
            con = (OutputConnection)Connector.open(name, Connector.WRITE);
        } catch (ClassCastException e) {
            throw new IOException(
/* #ifdef VERBOSE_EXCEPTIONS */
/// skipped                       e.toString()
/* #endif */
            );
        }

        try {
            return con.openDataOutputStream();
        } finally {
            con.close();
        }
    }

    /**
     * Create and open a connection input stream.
     *
     * @param  name            The URL for the connection.
     * @return                 An InputStream.
     *
     * @exception IllegalArgumentException If a parameter is invalid.
     * @exception ConnectionNotFoundException If the connection cannot
     *                                        be found.
     * @exception IOException  If some other kind of I/O error occurs.
     */
    public static InputStream openInputStream(String name)
        throws IOException {

        return openDataInputStream(name);
    }

    /**
     * Create and open a connection output stream.
     *
     * @param  name            The URL for the connection.
     * @return                 An OutputStream.
     *
     * @exception IllegalArgumentException If a parameter is invalid.
     * @exception ConnectionNotFoundException If the connection cannot
     *                                        be found.
     * @exception IOException  If some other kind of I/O error occurs.
     */
    public static OutputStream openOutputStream(String name)
        throws IOException {

        return openDataOutputStream(name);
    }

}

分享到:
评论

相关推荐

    Android与J2ME平台间即时通信的研究与实现

    该系统利用了Jabber服务器作为中间节点,通过XMPP协议在Android与J2ME平台之间建立了连接。具体来说,Android客户端使用Java的XMPP客户端库进行通信,而J2ME客户端由于资源限制,则使用轻量级的XMPP客户端库。在模拟...

    j2me2D游戏框架

    Java 2 Micro Edition (J2ME) 是一种用于开发小型设备和嵌入式系统的 Java 平台,尤其在早期的移动设备...虽然现代移动游戏开发更多转向了Android和iOS平台,但理解J2ME游戏框架对于学习游戏开发原理和技术仍有其价值。

    Android通过J2ME的录音功能实现简易示波器

    【Android通过J2ME的录音功能实现简易示波器】是一种利用J2ME的多媒体应用编程接口(MMAPI)在Android设备上构建一个简单的模拟示波器的方法。虽然使用智能机可以实现实时读取麦克风输入流,提供更流畅的体验,但...

    J2ME LODER源码

    J2ME LODER应包含解析JAR和JAD文件的逻辑,模拟J2ME应用的安装和启动过程。这涉及到应用签名验证、资源提取和类加载。 通过深入研究J2ME LODER的源码,开发者不仅可以学习到Android开发的知识,还可以了解到如何将...

    J2ME工具篇.rar

    10. **J2ME测试框架**:例如JUnit,尽管主要针对Java SE,但也可以通过适配器应用于J2ME项目,用于编写和运行单元测试,确保代码质量。 在J2ME开发过程中,选择适合项目需求的工具组合至关重要。理解这些工具的功能...

    J2ME游戏源代码

    通过分析这些J2ME游戏源代码,你可以学习到如何在有限的硬件条件下创建引人入胜的游戏体验,掌握游戏设计、性能优化以及跨平台开发的技巧。同时,这也能帮助你了解移动游戏开发的历史,因为随着技术的发展,现代移动...

    J2ME开发手册

    例如,一个J2ME客户端可能通过HTTP协议连接到J2EE服务器,获取或发送数据。服务器端的servlet和jsp处理请求,返回响应。这种模式常见于移动应用的后端服务架构。 **学习J2ME的好处** 学习J2ME能拓宽Java开发者的...

    JAVA-zhuankuai(j2me).rar_J2ME游戏_j2me_j2me 游戏

    1. **MIDP (Mobile Information Device Profile)**:这是J2ME的一个子集,为移动设备定义了基本的应用程序框架。它包含了用户界面组件、网络连接支持以及数据存储功能。 2. **CLDC (Connected Limited Device ...

    J2ME手机游戏开发引擎的分析与设计

    本文主要探讨了J2ME手机游戏引擎的开发,这种引擎能够帮助开发者快速构建J2ME平台上的游戏,通过自定义参数生成游戏框架,使得程序员可以专注于游戏逻辑的实现,提高开发效率并确保游戏质量。 1.1 开发的目的和意义...

    J2ME手机游戏开发毕业论文

    J2ME游戏的逻辑通常在事件驱动模型下运行,通过键盘、触摸屏输入或模拟按键来控制游戏。GameLoop是游戏循环的核心,负责更新游戏状态、渲染画面以及处理用户输入。 **五、性能优化** 由于J2ME设备的硬件限制,性能...

    J2ME无线设备编程

    例如,Mobile Information Device Profile (MIDP)是用于开发移动设备应用程序的J2ME框架,提供了用户界面组件、网络连接和数据存储等功能。 在进行**J2ME无线设备编程**时,开发者通常会使用K Java编辑器或者...

    J2ME在移动设备上的应用

    开发J2ME应用通常需要一个集成开发环境(IDE),如NetBeans或Eclipse,它们提供了编写、编译、调试和模拟J2ME应用的工具。此外,Sun Microsystems(现为Oracle)提供的K Java SDK是开发J2ME应用的基础,包括MIDP和...

    J2ME API.CHM

    此外,还有专门的J2ME开发工具,如J2ME Wireless Toolkit (J2ME WTK),用于模拟和测试J2ME应用程序。 **6. 应用场景** J2ME广泛应用于手机游戏开发、移动银行应用、位置服务、消息推送等。通过J2ME API,开发者可以...

    基于J2ME (Java 2 Micro Edition)的手机游戏开发

    J2ME为开发者提供了开发手机游戏的强大工具,虽然现在已经被更先进的技术如Android和iOS SDK取代,但在过去,J2ME曾是移动游戏开发的主流。理解其架构和开发流程,对于了解早期移动开发历史和现有技术的演进有着重要...

    J2ME 手机程序开发

    尽管现在Android和iOS占据了主导地位,但在某些特定市场,如功能手机,J2ME仍然有一定的应用空间。 以上就是关于J2ME手机程序开发的一些核心知识点,对于想学习或从事移动应用开发的人来说,理解和掌握这些概念是...

    java j2me的游戏引擎

    Java J2ME游戏引擎是为在Java Micro Edition (J2ME)平台上开发移动游戏而设计的一种软件框架。J2ME是一种轻量级的Java平台,主要用于嵌入式设备,如早期的智能手机和平板电脑,它提供了运行Java应用程序的能力,包括...

    j2me 记事本

    Java 2 Micro Edition (J2ME) 是一个Java平台,专为嵌入式设备和移动设备设计...尽管现代移动平台可能倾向于使用更高级的开发框架,如Android Studio和iOS的Swift,但J2ME仍然是学习移动开发和理解基本原理的重要起点。

    手机开发代码 J2ME

    总的来说,J2ME是移动开发史上的一个重要里程碑,虽然随着Android和iOS的兴起,其在现代智能手机领域的应用逐渐减少,但在物联网和一些低功耗设备上,J2ME依然有其存在价值。了解J2ME的基本原理和实践技巧,对于理解...

    WTK2.2 J2ME开发工具下载

    3. **库文件**:WTK提供了一系列的基础类库,包括 MIDP (Mobile Information Device Profile) 和 CLDC (Connected Limited Device Configuration),这些都是开发J2ME应用程序的基础框架。 4. **示例代码**:WTK2.2...

Global site tag (gtag.js) - Google Analytics