Motorola Inc.

i88s J2ME Developers’ Guide

StreamConnection sc =(StreamConnection)Connector.open(String name, int mode, boolean timeout);

name = “file://temp.txt” and mode may have three values: Connector.READ, Connector.WRITE, and Connector.READ_WRITE. The third parameter, timeout, has no effect on the interface.

The open method of the Connector class returns a StreamConnection object for file access, which implements InputConnection and OutputConnection. The InputConnection and OutputConnection have methods for getting input and output streams. Base interface Connection has a method to close the file. (Refer to the class hierarchy of StreamConnection from the CLDC 1.0 specification).

3.3.2 Deleting a file

An application can delete a file in the following manner:

StreamConnection sc=(StreamConnection)Connector.open(String name);

Where name = “file://temp.txt;DELETE”; is entered, “temp.txt” will be deleted. In addition, if the file cannot be deleted, an I/O Exception will be thrown.

NOTE: All the InputStreams, OutputStreams and StreamConnections associated with a file should be closed before deleting the file.

3.3.3Reading and Writing

Since the File IO class utilizes the Generic Connection Framework, reading and writing to a file is accomplished by standard InputStream and OutputStream APIs.

3.4Code Examples

Example # 1 (file snippet)

The following example shows how to open a file, write bytes to the file and read the same number of bytes.

StreamConnection sc = null; InputStream is = null; OutputStream os = null;

String name = “file://temp.txt”; try {

// open a file, default mode: READ_WRITE

sc = (StreamConnection)Connector.open(name); // get OutputStream

os = sc.openOutputStream(); // get InputStream

is = sc.openInputStream(); String b = “Hello World”;

//write the bytes os.write(b.getBytes());

int dataAvailable = is.available(); byte [] b1 = new byte[dataAvailable];

//read the bytes

Version 1.0 - Page 23

Page 23
Image 23
Motorola i88s manual Deleting a file, Reading and Writing, Code Examples