当前位置: 代码迷 >> Android >> Android 模拟J2me 透过连接框架
  详细解决方案

Android 模拟J2me 透过连接框架

热度:123   发布时间:2016-05-01 15:32:19.0
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: [email protected] 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);
??? }

}