You are on page 1of 13

Sun

Java

Solaris

Communities

My SDN Account

APIs

Do wnlo ads

Pro duct s

Suppo rt

Training

Part icipat e

search tips

Search

SDN Home > Mobility > Reference > Technical Articles and Tips >

Article

Getting Started with the FileConnection APIs


By Qusay Mahmoud, December 2004

The Co nnected Limited Device Co nfiguratio n (CLDC) and the mo st po pular pro file based o n it, the Mo bile Info rmatio n Device Pro file (MIDP), fo cus o n pro viding a so und runtime enviro nment and basic applicatio n services. Neither the co nfiguratio n no r the pro file includes APIs fo r access to file systems o n mo bile devices o r external memo ry cards. This o missio n is intentio nal: No t all MIDP devices have file systems, and the creato rs o f tho se that do may no t want to expo se them to applicatio ns. The Java 2 Platfo rm, Standard Editio n (J2SE) includes java.io .File and its related classes to suppo rt such access, but these APIs are to o heavyweight to be useful o n mo bile devices. The so lutio n lies in the FileCo nnectio n Optio nal Package, a simple but useful set o f file-system APIs fo r the Java 2 Platfo rm, Micro Editio n (J2ME). This o ptio nal package is part o f JSR 75, PDA Optio nal Packages fo r the J2ME Platfo rm . On devices that implement JSR 75, this package enables J2ME-based applicatio ns to create, read, and write files and directo ries lo cated o n mo bile devices and external memo ry cards. This tuto rial pro vides a co de-intensive intro ductio n to the FileCo nnectio n APIs; it: Intro duces JSR 75 Describes the javax.micro editio n.io .file package Pro vides details o f the FileCo nnectio n APIs Gives yo u a taste o f the effo rt invo lved in using these APIs Pro vides co de yo u can adapt to yo ur o wn wireless applicatio ns Opt io nal Package s f o r t he J 2ME Plat f o rm JSR 75 pro vides so me very useful APIs that J2ME develo pers really needed to take advantage o f features co mmo nly fo und o n PDAs in the J2ME space, in the fo rm o f two o ptio nal packages that extend and enhance so ftware stacks based o n CLDC: 1. The FileCo nnectio n Optio nal Package (FC) APIs give J2ME devices access to file systems residing o n mo bile devices, primarily access to remo vable sto rage media such as external memo ry cards. 2. The PIM Optio nal Package (PIM) APIs give J2ME devices access to perso nal info rmatio n management data native to mo bile devices, such as address bo o ks, calendars, and to -do lists. It's impo rtant to no te that the FC and PIM packages are independent o f each o ther. This article will fo cus o n the FileCo nnectio n APIs. Because any device that meets the minimum requirements o f CLDC 1.0 can also suppo rt JSR 75, and because the Co nnected Device Co nfiguratio n (CDC) is a superset o f CLDC, the FileCo nnectio n APIs can be deplo yed o n to p o f any CLDC- o r CDC-based pro file.
PDFmyURL.com

No t e : In the phrase "o ptio nal package," the wo rd "o ptio nal" indicates that who ever is respo nsible fo r maintaining the platfo rm so ftware o n the device, usually the manufacturer, has the o ptio n to include implementatio n o f the API. In general, neither end users no r applicatio n develo pers can do wnlo ad an o ptio nal package and install it in the device. An applicatio n that relies o n an o ptio nal package will run pro perly o nly if that package is already installed. T he File Co nne ct io n Opt io nal Package To gain access to file systems lo cated in a device's internal memo ry, o r o n remo vable memo ry media such as SmartMedia cards and Co mpactFlash cards, the FC APIs use the Generic Co nnectio n Framewo rk (GCF) fo r file-system co nnectivity. T he File Co nne ct io n APIs The FC APIs are defined in the package javax.microedition.io.file, which includes two interfaces and three classes: Int e rf ace FileConnection FileSystemListener Class FileSystemRegistry De script io n Interface fo r access to files o r directo ries. Listener interface fo r receiving status no tificatio n when adding o r remo ving a file-system ro o t. De script io n Central registry fo r listeners that need to add o r remo ve a file system.

ConnectionClosedException Exceptio n thro wn when a metho d o f a file co nnectio n is invo ked but canno t be co mpleted because the co nnectio n is clo sed. IllegalModeException Exceptio n thro wn when a metho d is invo ked that requires a particular security mo de, such as READ o r WRITE, but the co nnectio n o pened is no t in that mo de.

The FC o ptio nal package may no t be available o n all J2ME platfo rms. To find o ut whether it is, invo ke System.getproperty() with a key o f microedition.io.file.FileConnection.version. This metho d will return the versio n number o f the API if the package is present, null if it's no t. Ano ther useful pro perty is the file.separator, a string representing the file separato r character, "/" fo r example. No t e : CLDC permits implementatio ns to refuse to lo ad an applicatio n that refers to classes that aren't present, so a device that do esn't have the FileCo nnectio n APIs installed might no t let yo ur applicatio n check fo r them at runtime. In this case, yo u must be prepared to package two different versio ns o f the applicatio n, o ne that uses the FileCo nnectio n APIs and o ne that do esn't. Se curit y Issue s In additio n to including all packages, classes, and interfaces defined in the FileCo nnectio n o ptio nal package, a JSR 75-co mpliant implementatio n must also pro vide a security mo del fo r accessing the FileCo nnectio n APIs. In particular: To pro tect users' files and data fro m inadvertent o r malicio us access, an implementatio n may allo w access to files that are public and bar access to files that are private o r sensitive. The implementatio n may no t allo w access to MIDP RMS databases, and sho uld no t allo w access to system co nfiguratio n files, o r to files and directo ries that are device- o r OS-specific, private to ano ther applicatio n, o r private to a different user. In such cases the Connector.open() metho d thro ws a java.lang.SecurityException. The security mo del must be applied when o pening a co nnectio n to a file using Connector.open() and when o pening a stream fo r the co nnectio n using openInputStream(), openOutputStream(), openDataInputStream(), o r openDataOutputStream().
PDFmyURL.com

Again, it's up to the including platfo rm o r pro file to define a security mo del. There is o ne special case: The JSR 75 expert gro up has pro vided a reco mmended practice fo r using the FileCo nnectio n APIs when the including pro file is MIDP 2.0 , which states: Untrusted MIDlet suites that access the pro tected APIs and functio ns o f the FileCo nnectio n APIs must be subject to co nfirmatio n by the user. Trusted MIDlet suites must specify the permissio ns that are applicable to the FileCo nnectio n APIs. Fo r mo re info rmatio n o n the permissio ns and pro tected metho ds, please refer to the FC specificatio n. Est ablishing Co nne ct io ns An applicatio n o pens a co nnectio n using Connector.open(). The input string must co mprise a fully qualified, abso lute pathname o f the fo rm file://<host>/<root>/<directory>/<directory>/.../<name>. The ho st element may be empty - and o ften will be, when the string refers to a file o n the lo cal ho st. The ro o t directo ry co rrespo nds to a lo gical mo unt po int fo r a particular sto rage unit. Ro o t names are device-specific. The fo llo wing table pro vides so me examples o f ro o t values and ho w to o pen them: Ro o t Value CFCard/ SDCard/ MemoryStick/ C:/ / Ho w t o Ope n a File Co nne ct io n FileConnection fc = (FileConnection) Connector.open("file:///CFCard/"); FileConnection fc = (FileConnection) Connector.open("file:///SDCard/"); FileConnection fc = (FileConnection) Connector.open("file:///MemoryStick/"); FileConnection fc = (FileConnection) Connector.open("file:///C:/"); FileConnection fc = (FileConnection) Connector.open("file:////");

No te well that a co nnectio n o bject like fc in these examples refers to a single file o r directo ry at any given time. The best way to refer to multiple directo ries o r files is to establish a separate co nnectio n to each, using Connector.open(). Once yo u've established a co nnectio n to a file system, yo u can perfo rm several kinds o f queries, using the FileCo nnectio n o bject's metho ds, including amo ng o thers: Ge t a f ilt e re d list o f f ile s and dire ct o rie s using the metho d list(String filter, boolean includeHidden). In the filter parameter yo u can use * as a wildcard to specify zero o r mo re o ccurences o f any character. The includeHidden parameter specifies whether yo u want to list o nly visible files, o r hidden files as well. Disco ve r whe t he r a f ile o r dire ct o ry e xist s using exists(). Disco ve r whe t he r a f ile o r dire ct o ry is hidde n using isHidden(). Cre at e o r de le t e a f ile o r dire ct o ry using create(), mkdir(), o r delete(). Fo r a list o f all the valid ro o t values in a device, call the listRoots() metho d o f FileSystemRegistry. No te that a FileConnection behaves differently fro m o ther Generic Co nnectio n Framewo rk co nnectio ns in o ne way: The Connector.open() metho d can return successfully witho ut referring to an existing entity such as a file o r a directo ry. This capability enables yo u to create new files and directo ries. Here is a segment o f co de that creates a new file; assume SDCard is a valid file-system ro o t:

public void createFile() { PDFmyURL.com

public void createFile() { 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) { } }

Re f e re nce Im ple m e nt at io ns The o fficial reference implementatio n o f JSR 75 can be do wnlo aded fro m IBM. This RI is aimed at the Po cketPC o perating system, so it requires the J9 Java Virtual Machine fo r the Po cketPC. An implementatio n o f JSR 75 is included in the beta release in the J2ME Wireless To o lkit 2.2 fro m Sun Micro systems. We'll use the to o lkit to test the examples in the rest o f this article. File Co nne ct io n De m o in J 2ME Wire le ss To o lkit 2.2 The J2ME Wireless To o lkit 2.2 co mes with a FileCo nnectio n demo : a file bro wser that lets the user list files and directo ries and view the co ntents o f text files. To experiment with this demo , do wnlo ad the to o lkit and install it if yo u haven't already do ne so ; then: 1. Start KTo o lbar. 2. Open the pro ject PDAPDemo . 3. Run the applicatio n. No te that because the applicatio n is go ing to bro wse lo cal files, yo u're pro mpted to give permissio n, as sho wn in Figure 1. Figure 1: User Confirmation for Access

PDFmyURL.com

4. Once permissio n is granted, yo u can begin to bro wse the file system, as in Figure 2: Figure 2: Browsing the File System

PDFmyURL.com

5. Select the root1 directo ry, then o pen the file Readme to see the co ntents o f that file, sho wn in Figure 3: Figure 3: Viewing a File's Contents

PDFmyURL.com

No t e : The J2ME Wireless To o lkit emulato r sets aside a directo ry o n yo ur deskto p co mputer's hard disk, /<toolkit>/appdb/DefaultColorPhone/filesystem , to ho ld representatio ns o f a mo bile device's file-system ro o ts. It then uses the FileCo nnectio n APIs to give MIDlets access to files sto red in subdirecto ries o f filesystem . The emulato r co mes with o ne ro o t directo ry already installed, called root1, which co ntains the file Readme. In the to o lkit emulato r, each immediate subdirecto ry o f filesystem is treated as a ro o t. Using t he File Co nne ct io n APIs To give yo u an idea ho w little effo rt is invo lved in using the FileCo nnectio n APIs, we'll examine a simple applicatio n that allo ws yo u to list the valid ro o ts as well as the files and directo ries in a particular ro o t. To start, yo u need to set up the valid ro o ts as fo llo ws: 1. 2. 3. 4. Go to /toolkit/appdb/DefaultColorPhone/filesystem ; yo u'll no tice that a subdirecto ry, root1, already exists. In filesystem create two new subdirecto ries and call them CFCard and SDCard. In CFCard create a new subdirecto ry called pix. In CFCard create two new files and name them readme.txt and personal.txt. Write a few lines in each so that later yo u can check file sizes. If yo u think yo u'll want to experiment with the includeHidden parameter to FileConnection.list(), flag o ne o f the files as hidden. No te that under Windo ws yo u can do so with the co mmand attrib +h <filename>.

/<toolkit>/appdb/DefaultColorPhone/filesystem/ CFCard/ readme.txt personal.txt pix/ SDCard/ PDFmyURL.com

The FileConnectionDemo MIDlet in Co de Sample 1 demo nstrates ho w to use the FileCo nnectio n APIs to access files and directo ries. Two metho ds deserve special attentio n: getRoots() uses FileSystemRegister.listRoots() to list the valid ro o t values. GetCFcardContent() iterates thro ugh the list o f files and directo ries under the CFCard/ ro o t value. Fo r each, the metho d indicates whether it's a file o r directo ry, displays its name, and if it's a file repo rts its size. Code Sample 1: FileConnectionDemo.java

import import import import import

java.io.*; java.util.*; javax.microedition.io.*; javax.microedition.midlet.*; 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

System.out.println ("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-co des the ro o t "CFCard/" po o r practice in anything but a demo nstratio n, o f co urse. Yo u co uld impro ve this MIDlet by using the listRoots() metho d as sho wn earlier to o btain the valid ro o t values. At this po int, tho ugh, experiment with FileConnectionDemo as it stands: 1. Start KTo o lbar. 2. Create a new pro ject and call it anything yo u like FC in my example but do name the MIDlet FileConnectionDemo. 3. Co nfigure the pro ject to include JSR 75 as sho wn in Figure 4: Figure 4: Configuring the Project to Use JSR 75

PDFmyURL.com

4. Co py the pro gram in Co de Sample 1, and in /<toolkit>/apps/FC/ save it as FileConnectionDemo.java. 5. Build and run the applicatio n. Yo u'll see it repo rts the directo ry structure yo u created earlier, as in Figure 5: Figure 5: Listing of Roots, Files, and Directories

PDFmyURL.com

If yo u run the to o lkit's FileBrowser demo again, yo u'll see o utput similar to Figure 6 : Figure 6: The New Directory Structure, Reported by FileBrowser

The pro gram in Co de Sample 1 lists ro o ts, files, and directo ries, but do esn't display the co ntents o f any file. The fo llo wing metho d handles this cho re. No te that the co ntents appear o n the co nso le but yo u can easily change the co de to display them in a bo x o n the device's display.
PDFmyURL.com

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) { } }

Co nclusio n JSR 75 defines two APIs: the PIM Optio nal Package and the FileCo nnectio n Optio nal Package. The first o f these interfaces give J2ME-based applicatio ns easy access to perso nal info rmatio n management data that resides o n mo bile devices, o ften in a native fo rm, such as address bo o ks, calendars, and to -do lists. The seco nd interface pro vides similar access to co nventio nal hierarchical file systems residing o n mo bile devices and external memo ry cards. This article intro duced the PDA Optio nal Packages fo r the J2ME Platfo rm, and presented a tuto rial o n the FileCo nnectio n APIs. The sample co de sho wed ho w easy it is to develo p MIDlets that give their users access to device-lo cal file systems. Learn o nly a handful o f classes and interfaces and yo u're ready to begin. Remember that the FileCo nnectio n APIs are part o f an o ptio nal package that may no t be available o n all J2ME devices. Fo r Mo re Inf o rm at io n JSR 75: PDA Optio nal Packages fo r the J2ME Platfo rm J2ME Wireless To o lkit 2.2 IBM's JSR 75 Reference Implementatio n No kia 6 6 30 Smartpho ne Ackno wle dge m e nt s Special thanks to Stuart Marks o f Sun Micro systems, who se feedback helped me impro ve this article. Abo ut t he Aut ho r Qusay H. Mahmo ud pro vides Java techno lo gy co nsulting and training services. He has published do zens o f Java articles, and is the autho r o f Distributed Programming with Java (Manning Publicatio ns, 19 9 9 ) and Learning Wireless Java (O'Reilly, 20 0 2). Rat e and Re vie w Tell us what yo u think o f the co ntent o f this page. Exce lle nt Go o d Fair Po o r
PDFmyURL.com

Co m m e nt s:

Yo ur e m ail addre ss (no re ply is po ssible wit ho ut an addre ss): Sun Privacy Po licy No te: We are no t able to respo nd to all submitted co mments. Subm it

Oracle is reviewing the Sun pro duct ro admap and will pro vide guidance to custo mers in acco rdance with Oracle's standard pro duct co mmunicatio n po licies. Any resulting features and timing o f release o f such features as determined by Oracle's review o f ro admaps, are at the so le discretio n o f Oracle. All pro duct ro admap info rmatio n, whether co mmunicated by Sun Micro systems o r by Oracle, do es no t represent a co mmitment to deliver any material, co de, o r functio nality, and sho uld no t be relied upo n in making purchasing decisio ns. It is intended fo r info rmatio n purpo ses o nly, and may no t be inco rpo rated into any co ntract.

Abo ut Sun | Abo ut This Site | Newsletters | Co ntact Us | Emplo yment | Ho w to Buy | Licensing | Terms o f Use | Privacy | Trademarks

A Sun De ve lo pe r Ne t wo rk Sit e Unless o therwise licensed, co de in all technical manuals herein (including articles, FAQs, samples) is pro vided under this License. Sun Develo per RSS Feeds

20 10 , Oracle Co rpo ratio n and/o r its affiliates

PDFmyURL.com

You might also like