+ All Categories
Home > Documents > Arquivos J2Me

Arquivos J2Me

Date post: 07-Apr-2018
Category:
Upload: tiago-balbino
View: 234 times
Download: 0 times
Share this document with a friend

of 13

Transcript
  • 8/6/2019 Arquivos J2Me

    1/13

    SDN Home > Mobility > Reference > Techni cal Articles and Tips >

    Article

    By Qusay Mahmoud, December 2004

    The Connected Limited Device Configuration (CLDC) and the mo st po pular profile based o n it, the Mobile Informatio n Device Profile (MIDP), focuson pro viding a so und runtime environment and basic application services. Neither the configuration no r the profile includes APIs for access to filesystems on mo bile devices or external memo ry cards. This omis sio n is intentional: Not all MIDP devices have file systems , and the creators o fthose that do may not want to expos e them to applications .

    The Java 2 Platform, Standard Edition (J2SE) includes java.io.File and its related classes to suppo rt such access, but these APIs are tooheavyweight to be useful o n mo bile devices. The solution lies in the FileConnection Optio nal Package, a sim ple but useful set of file-system APIsfor the Java 2 Platform, Micro Edition (J2ME). This o ptional package is part o f JSR 75, PDA Optional Packages fo r the J2ME Platform . On devices

    that implement JSR 75, this package enables J2ME-bas ed applications to create, read, and write files and directories lo cated on mo bile devicesand external memory cards.

    This tutorial provides a code-intensive introduction to the FileConnection APIs; it:

    Introduces J SR 75Describes the javax.microeditio n.io.file packageProvides details of the FileConnection APIsGives you a taste of the effort involved in using these APIsProvides code you can adapt to yo urown wireless applications

    Optional Packages fo r the J2ME Platf orm

    JSR 75 provides so me very useful APIs that J2ME developers really needed to take advantage of features co mmo nly found on PDAs in the J2ME

    space, in the form o f two optional packages that extend and enhance software stacks based o n CLDC:

    1. The FileConnection Optional Package (FC) APIs give J2ME devices access to file systems residing o n mo bile devices, primarily access toremovable sto rage media such as external memo ry cards.

    2. The PIM Optional Package (PIM) APIs give J2ME devices access to perso nal information m anagement data native to mo bile devices, such asaddress books, calendars, and to-do lists.

    It's impo rtant to note that the FC and PIM packages are independent o f each other. This article will fo cus o n the FileConnection APIs.

    Because any device that meets the minim um requirements o f CLDC 1.0 can als o suppo rt JSR 75, and because the Connected DeviceConfiguration (CDC) is a superset o f CLDC, the FileConnection APIs can be deployed on top of any CLDC- o r CDC-based profile.

    Getting Started with the FileConnection APIs

    search tips SearchAP Is Do wnlo ads P ro duct s S uppo rt Traini ng P art ici pat e

    Sun Java Solaris Communities My SDN Account

    PDFmyURL.com

    http://www.jcp.org/en/jsr/detail?id=75http://developers.sun.com/http://developers.sun.com/mobility/index.jsphttp://developers.sun.com/mobility/reference/index.jsphttp://developers.sun.com/mobility/reference/techart/index.jsphttp://developers.sun.com/global/mh/api/index.htmlhttp://developers.sun.com/global/mh/downloads/index.htmlhttp://developers.sun.com/global/mh/products/index.htmlhttp://developers.sun.com/global/mh/support/index.htmlhttp://developers.sun.com/global/mh/training/index.htmlhttp://developers.sun.com/global/mh/participate/index.htmlhttp://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://www.jcp.org/en/jsr/detail?id=75http://slashdot.org/bookmark.pl?title=Getting%20Started%20with%20the%20FileConnection%20APIs&url=http%3A%2F%2Fdevelopers.sun.com%2Fmobility%2Fapis%2Farticles%2Ffileconnection%2Fhttp://digg.com/submit?phase=2&url=http%3A%2F%2Fdevelopers.sun.com%2Fmobility%2Fapis%2Farticles%2Ffileconnection%2F&title=Getting%20Started%20with%20the%20FileConnection%20APIshttp://del.icio.us/post?v=4;url=http%3A%2F%2Fdevelopers.sun.com%2Fmobility%2Fapis%2Farticles%2Ffileconnection%2F;title=Getting%20Started%20with%20the%20FileConnection%20APIshttp://technorati.com/search/http%3A%2F%2Fdevelopers.sun.com%2Fmobility%2Fapis%2Farticles%2Ffileconnection%2Fmailto:?subject=Sun%20Web%20Page:%20Getting%20Started%20with%20the%20FileConnection%20APIs&body=Check%20out%20this%20page%20on%20sun.com:%20%0A%0Ahttp%3A%2F%2Fdevelopers.sun.com%2Fmobility%2Fapis%2Farticles%2Ffileconnection%2Fhttp://developers.sun.com/mobility/reference/techart/index.jsphttp://developers.sun.com/mobility/reference/index.jsphttp://developers.sun.com/mobility/index.jsphttp://developers.sun.com/http://developers.sun.com/global/mh/participate/index.htmlhttp://developers.sun.com/global/mh/training/index.htmlhttp://developers.sun.com/global/mh/support/index.htmlhttp://developers.sun.com/global/mh/products/index.htmlhttp://developers.sun.com/global/mh/downloads/index.htmlhttp://developers.sun.com/global/mh/api/index.htmlhttp://developers.sun.com/global/search_tips.htmlhttp://developers.sun.com/global/my_profile.htmlhttp://developers.sun.com/global/mh/communities/http://developers.sun.com/global/mh/solaris/http://developers.sun.com/global/mh/java/http://developers.sun.com/global/mh/suncom/index.html
  • 8/6/2019 Arquivos J2Me

    2/13

    Note: In the phrase "o ptional package," the word "o ptional" indicates that whoever is respo nsible for maintaining the platformso ftware o n the device, usually the manufacturer, has the o ption to include implementation of the API. In general, neither end usersnor application developers can downlo ad an optional package and install it in the device. An application that relies on an o ptionalpackage will run properly o nly if that package is already installed.

    The FileConnect ion Optio nal Package

    To gain access to file systems located in a device's internal memo ry, or on remo vable memo ry media such as SmartMedia cards andCom pactFlash cards, the FC APIs us e the Generic Connection Framework (GCF) for file-system connectivity.

    The FileConnectio n APIs

    The FC APIs are defined in the package javax.microedition.io.file, which includes two interfaces and three classes:

    Int erf ace Descript ion

    FileConnection Interface for access to files o r directories .

    FileSystemListener Listener interface for receiving status no tification when adding o r removing a file-s ystem roo t.

    Class Descript ion

    FileSystemRegistry Central registry for listeners that need to add o r remove a file s ystem.

    ConnectionClosedException Exception thrown when a m ethod of a file connection is invoked but cannot be completed because the

    connection is closed.

    IllegalModeException Exception thrown when a method is invo ked that requires a particular security mo de, such as READ o r WRITE,but the connection o pened is no t in that mo de.

    The FC optional package may no t be available on all J2ME platforms. To find out whether it is, invoke System.getproperty()with a key of

    microedition.io.file.FileConnection.version. This method will return the version num ber of the API if the package is present, null if it's

    not. Another useful property is the file.separator, a s tring representing the file separator character, "/" fo r example.

    Note: CLDC permits implem entations to refuse to lo ad an application that refers to clas ses that aren't present, so a device thatdoes n't have the FileConnection APIs installed might no t let your application check for them at runtime. In this case, you m ust beprepared to package two di fferent versio ns o f the application, o ne that uses the FileConnection APIs and o ne that doesn't.

    Security Issues

    In addition to including all packages, classes, and interfaces defined in the FileConnection o ptional package, a JSR 75-compliant implem entationmust als o pro vide a security model for accessing the FileConnection APIs. In particular:

    To pro tect users' files and data from inadvertent or malicious access, an implementation may allo w access to files that are public and baraccess to files that are private or sens itive. The implementation m ay not allow access to MIDP RMS databases, and should no t allow access tosystem co nfiguration files , or to files and directories that are device- o r OS-specific, private to ano ther application, o r private to a different user.In such cases the Connector.open()method throws a java.lang.SecurityException.

    The security model m ust be applied when opening a connection to a file using Connector.open()and when opening a stream for the

    connection using openInputStream(), openOutputStream(), openDataInputStream(), oropenDataOutputStream().

    PDFmyURL.com

    http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.01
  • 8/6/2019 Arquivos J2Me

    3/13

    Again, it's up to the including platform o r profile to define a security mo del. There is one s pecial case: The JSR 75 expert group has provided arecomm ended practice for using the FileConnection APIs when the including profile is MIDP 2.0, which states:

    Untrusted MIDlet suites that access the protected APIs and functions of the FileConnection APIs mus t be subject to confirmation by the us er.Trusted MIDlet suites must specify the permiss ions that are applicable to the FileConnection APIs. For mo re information on the permissio ns

    and protected methods, pleas e refer to the FC specification.

    Establishing Connect ions

    An application opens a connection using Connector.open(). The input string mus t comprise a fully qualified, abso lute pathname of the formfile://////.../. The host element may be em pty - and o ften will be, when the string refers to

    a file on the local ho st. The roo t directory corresponds to a lo gical mo unt point for a particular storage unit. Roo t names are device-specific. Thefollowing table provides some examples of root values and how to open them:

    Ro ot Value Ho w t o Ope n a File Co nnect io n

    CFCard/ FileConnection fc = (FileConnection) Connector.open("file:///CFCard/");

    SDCard/ FileConnection fc = (FileConnection) Connector.open("file:///SDCard/");

    MemoryStick/ FileConnection fc = (FileConnection) Connector.open("file:///MemoryStick/");

    C:/ FileConnection fc = (FileConnection) Connector.open("file:///C:/");

    / FileConnection fc = (FileConnection) Connector.open("file:////");

    Note well that a connection o bject like fc in these examples refers to a single file o r directory at any given time. The best way to refer to multipledirectories or files is to es tablish a separate connection to each, using Connector.open().

    Once you've established a connection to a file system, you can perform s everal kinds o f queries, using the FileConnection object's methods ,including among others:

    Get a f iltered list of files and directo ries using the method list(String filter, boolean includeHidden). In the filter parameter

    you can us e * as a wildcard to specify zero or m ore o ccurences o f any character. The includeHiddenparameter specifies whether you want to

    list only visible files, or hidden files as well.Discover whether a f ile or directo ry exists using exists().

    Discover whether a f ile o r directory is hidden using isHidden().

    Create o r delete a f ile or directory using create(), mkdir(), ordelete().

    For a list o f all the valid root values in a device, call the listRoots()method ofFileSystemRegistry.

    Note that a FileConnection behaves differently from other Generic Connection Framework co nnections in o ne way: The Connector.open()

    method can return success fully without referring to an existing entity such as a file or a directory. This capability enables you to create new files anddirectories. Here is a segment of code that creates a new file; assum e SDCard is a valid file-system ro ot:

    ublic void createFile() {

    PDFmyURL.com

    http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.01
  • 8/6/2019 Arquivos J2Me

    4/13

    try {FileConnection filecon = (FileConnection)

    Connector.open("file:///SDCard/mynewfile.txt");

    // Always check whether the file or directory exists.// Create the file if it doesn't exist.if(!filecon.exists()) {

    filecon.create();}filecon.close();

    } catch(IOException ioe) {}

    }

    Reference Implementations

    The official reference implementation of J SR 75 can be downlo aded from IBM. This RI is aimed at the PocketPC operating system, so it requiresthe J9 Java Virtual Machine for the PocketPC. An implementation o f JSR 75 is included in the beta release in the J2ME Wireless Toolkit 2.2 fromSun Microsystems . We'll use the too lkit to test the examples in the rest of this article.

    FileConnectio n Demo in J 2ME Wireless Toolkit 2.2

    The J2ME Wireless Too lkit 2.2 comes with a FileCo nnection demo : a file browser that lets the user list files and directories and view the contentsof text files. To experiment with this demo , downlo ad the toolkit and ins tall it if you haven't already done so ; then:

    1. Start KToo lbar.

    2. Open the project PDAPDemo .3. Run the application. Note that because the application is go ing to browse lo cal files, you're prom pted to give permiss ion, as sho wn in Figure

    1.

    Figure 1: User Confirmation for Access

    PDFmyURL.com

    http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://java.sun.com/products/j2mewtoolkit/download-2_2.htmlhttp://www-128.ibm.com/developerworks/library/j-pda-op/
  • 8/6/2019 Arquivos J2Me

    5/13

    4. Once permissio n is granted, you can begin to browse the file system, as in Figure 2:

    Figure 2: Browsing the File System

    PDFmyURL.com

    http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.01
  • 8/6/2019 Arquivos J2Me

    6/13

    5. Select the root1 directory, then open the file Readme to see the contents of that file, sho wn in Figure 3:

    Figure 3: Viewing a File's Contents

    PDFmyURL.com

    http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.01
  • 8/6/2019 Arquivos J2Me

    7/13

    Note: The J2ME Wireless Toolkit emulator s ets aside a directory on your des ktop computer's hard disk,//appdb/DefaultColorPhone/filesystem, to ho ld representations of a mobi le device's file-system roo ts. It then

    uses the FileConnection APIs to give MIDlets access to files s tored in subdirectories o ffilesystem . The emulator comes with one

    roo t directory already installed, called root1, which contains the file Readme. In the too lkit emulator, each immediate subdirectory of

    filesystem is treated as a root.

    Using the FileCo nnection APIs

    To give yo u an idea how little effort is invo lved in using the FileConnection APIs, we'll examine a sim ple application that allows you to list the validroo ts as well as the files and directories in a particular root. To s tart, you need to set up the valid roots as follo ws:

    1. Go to /toolkit/appdb/DefaultColorPhone/filesystem; you'll notice that a subdirectory, root1, already exists.

    2. In filesystem create two new s ubdirectories and call them CFCard and SDCard.

    3. In CFCard create a new s ubdirectory called pix.4. In CFCard create two new files and name them readme.txt and personal.txt. Write a few lines in each s o that later you can check file

    siz es. If you think you'll want to experiment with the includeHidden parameter to FileConnection.list(), flag one of the files as hidden.

    Note that under Windows you can do so with the comm and attrib +h .

    //appdb/DefaultColorPhone/filesystem/CFCard/

    readme.txt

    personal.txtpix/

    SDCard/

    PDFmyURL.com

    http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.01
  • 8/6/2019 Arquivos J2Me

    8/13

    The FileConnectionDemoMIDlet in Code Sample 1 demo nstrates how to use the FileConnection APIs to access files and directories. Two

    methods des erve special attention:

    getRoots() uses FileSystemRegister.listRoots() to list the valid root values.

    GetCFcardContent() iterates through the list o f files and directories under the CFCard/ roo t value. For each, the method indicates whether

    it's a file or directory, displays its name, and if it's a file reports its si ze.

    Code Sample 1: FileConnectionDemo.java

    import java.io.*;import java.util.*;

    import javax.microedition.io.*;import javax.microedition.midlet.*;import javax.microedition.io.file.*;

    public class FileConnectionDemo extends MIDlet {

    public void startApp() {System.out.println("MIDlet Started....");getRoots();

    GetSDcardContent();//showFile("readme.txt");

    }

    public void pauseApp() {}

    public void destroyApp(boolean condition) {notifyDestroyed();

    }

    private void getRoots() {

    Enumeration drives = FileSystemRegistry.listRoots();System.out.println("The valid roots found are: ");while(drives.hasMoreElements()) {

    String root = (String) drives.nextElement();

    System.out.println("\t"+root);}

    }

    private void GetSDcardContent() {

    try {FileConnection fc = (FileConnection)

    Connector.open("file:///CFCard/");// Get a filtered list of all files and directories.// True means: include hidden files.

    // To list just visible files and directories, use// list() with no arguments.System.out.println

    PDFmyURL.com

    http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.01
  • 8/6/2019 Arquivos J2Me

    9/13

    ("List of files and directories under CFCard:");Enumeration filelist = fc.list("*", true);while(filelist.hasMoreElements()) {

    String fileName = (String) filelist.nextElement();fc = (FileConnection)

    Connector.open("file:///CFCard/" + fileName);

    if(fc.isDirectory()) {System.out.println("\tDirectory Name: " + fileName);

    } else {

    System.out.println("\tFile Name: " + fileName +"\tSize: "+fc.fileSize());

    }

    }

    fc.close();} catch (IOException ioe) {

    System.out.println(ioe.getMessage());

    }}

    public void showFile(String fileName) {try {

    FileConnection fc = (FileConnection)

    Connector.open("file:///CFCard/" + fileName);if(!fc.exists()) {

    throw new IOException("File does not exist");

    }InputStream is = fc.openInputStream();byte b[] = new byte[1024];

    int length = is.read(b, 0, 1024);System.out.println

    ("Content of "+fileName + ": "+ new String(b, 0, length));

    } catch (Exception e) {}

    }}

    This example hard-codes the root "CFCard/" poo r practice in anything but a demonstration, of co urse. You co uld impro ve this MIDlet by using

    the listRoots()method as sho wn earlier to o btain the valid root values. At this po int, though, experiment with FileConnectionDemoas it

    stands:

    1. Start KToo lbar.2. Create a new project and call it anything you like FC in my example but do nam e the MIDlet FileConnectionDemo.

    3. Configure the project to include JSR 75 as sho wn in Figure 4:

    Figure 4: Configuring the Project to Use JSR 75

    PDFmyURL.com

    http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.01
  • 8/6/2019 Arquivos J2Me

    10/13

    4. Copy the program in Code Sample 1, and in //apps/FC/save it as FileConnectionDemo.java.

    5. Build and run the application. You'll s ee it reports the directory structure you created earlier, as i n Figure 5:

    Figure 5: Listing of Roots, Files, and Directories

    PDFmyURL.com

    http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.01
  • 8/6/2019 Arquivos J2Me

    11/13

    If you run the toolkit's FileBrowser demo again, you'll s ee output similar to Figure 6:

    Figure 6: The New Di rectory Structure, Reported by FileBrowser

    The program in Code Sample 1 lists ro ots, files, and directories, but does n't display the contents o f any file. The follo wing method handles thischore. Note that the contents appear on the cons ole but you can eas ily change the code to dis play them in a box o n the device's dis play.

    PDFmyURL.com

    http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.01
  • 8/6/2019 Arquivos J2Me

    12/13

    public void showFile(String fileName) {try {

    FileConnection fc = (FileConnection)

    Connector.open("file:///CFCard/" + fileName);if(!fc.exists()) {

    throw new IOException("File does not exist");

    }InputStream is = fc.openInputStream();byte b[] = new byte[1024];

    int length = is.read(b, 0, 1024);System.out.println

    ("Content of "+fileName + ": "+ new String(b, 0, length));

    } catch (Exception e) {}

    }

    Conclusion

    JSR 75 defines two APIs: the PIM Optional Package and the FileConnection Optional Package. The first of these interfaces give J 2ME-basedapplications easy access to pers onal informatio n management data that resides on mo bile devices, often in a native form, such as addressboo ks, calendars, and to-do l ists. The second interface provides sim ilar access to conventional hierarchical file systems res iding on mo biledevices and external memory cards.

    This article introduced the PDA Optional Packages for the J2ME Platform, and presented a tutorial o n the FileConnection APIs. The sam ple codesho wed how eas y it is to develop MIDlets that give their users access to device-lo cal file systems. Learn only a handful of classes and interfacesand you're ready to begin. Remem ber that the FileConnection APIs are part of an o ptional package that may not be available on all J2ME devices.

    For More Information

    JSR 75: PDA Optional Packages fo r the J2ME PlatformJ2ME Wireless Toolkit 2.2IBM's JSR 75 Reference ImplementationNokia 66 30 Smartphone

    Acknowledgements

    Special thanks to Stuart Marks of Sun Microsystems , whos e feedback helped me improve this article.

    About the Author

    Qusay H. Mahmoud provides J ava technolo gy consulting and training services. He has published doz ens of Java articles, and is the author ofDistributed Programming with Java (Manning Publications, 1999 ) and Learning Wireless Java (O'Reilly, 200 2).

    Rate and Review

    Tell us what you think o f the content of this page.

    Excellent Good Fair Poor

    PDFmyURL.com

    http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://MAILTO:%[email protected]%22/http://www.nokia.com/nokia/0,,58708,00.htmlhttp://www-106.ibm.com/developerworks/library/j-pda-ophttp://java.sun.com/products/j2mewtoolkit/download-2_2.htmlhttp://www.jcp.org/en/jsr/detail?id=75
  • 8/6/2019 Arquivos J2Me

    13/13

    Comments:

    Your em ail address (no reply is possible witho ut an address):Sun Privacy Policy

    Note: We are not able to respo nd to all submitted comments.

    Submit

    Oracle is reviewing the Sun product roadmap and will pro vide guidance to cus tomers in acco rdance with Oracle's s tandard product comm unication policies . Any resultingfeatures and timing o f release of s uch features as determined by Oracle's review of roadm aps, are at the sole discretion o f Oracle. All product roadmap i nformation, whethercomm unicated by Sun Micros ystems o r by Oracle, does not represent a commitment to deliver any material, code, or functionality, and should no t be relied upon in makingpurchasing decisions . It is intended for information purpos es o nly, and may not be incorporated into any contract.

    About Sun | About This Site | Newsletters | Contact Us | Employment | How to Buy | Licensing | Termsof Use | Privacy | Trademarks

    20 10, Oracle Corporation and/or its affiliates

    A Sun Developer Net workSite

    Unless otherwise licensed,code in all technical manualsherein (including articles,FAQs, samples ) is providedunder this License.

    Sun Developer RSS Feeds

    PDFmyURL.com

    http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://pdfmyurl.com/?otsrc=watermark&otclc=0.01http://developers.sun.com/global/content_feeds.htmlhttp://developers.sun.com/global/rss_sdn.htmlhttp://developers.sun.com/global/berkeley_license.htmlhttp://developers.sun.com/global/aboutsdn.htmlhttp://developers.sun.com/global/trademarks.htmlhttp://developers.sun.com/global/privacy.htmlhttp://developers.sun.com/global/termsofuse.htmlhttp://developers.sun.com/global/licensing.htmlhttp://developers.sun.com/global/howtobuy.htmlhttp://developers.sun.com/global/employment.htmlhttp://developers.sun.com/global/contact.htmlhttp://developers.sun.com/global/newsletters.htmlhttp://developers.sun.com/global/aboutsdn.htmlhttp://developers.sun.com/global/aboutsun.htmlhttp://www.oracle.com/index.htmlhttp://sun.com/privacy/

Recommended