Java Reference
In-Depth Information
Accessing File Systems
You perform read and write operations through the input and output stream classes from the
java.io
package. These streams are a standard part of the CLDC, as Chapter 4 shows.
To obtain a stream to a file in the file system, however, you first need to have an opened file
connection. For this, you will need to use the File Connection optional API.
The main interface of this API is the
FileConnection
interface. You obtain an instance of a
FileConnection
by using a method of the
javax.microedition.io.Connector
class. This class is
part of the Generic Connection Framework in CLDC. GCF is used primarily to make connections
through a network or a communications port (see Chapter 10).
Obtaining FileConnections from GCF
At this time, the important thing you need to know about GCF is that the following static method
of the
Connector
class can return a
FileConnection
instance:
public static Connection open(String URL, int mode) throws IOException,
IllegalArgumentException,
ConnectionNotFoundException, SecurityException
The URL to obtain a file connection will always start with “file:///”, indicating that a file is
accessed on the local host. The full syntax for the URL is actually “file://<hostname>/”, but
<hostname>
is omitted when local. The mode indicates the type of access you want for the file
connection. You can use
Connector.READ
,
Connector.WRITE
, or
Connector.READ_WRITE
. For example,
you may get an input stream to an existing
abc.txt
file on an SD card using the following:
FileConnection fc = (FileConnection) Connector.open("file:///SDCard/abc.txt",
Connector.READ);
InputStream is = fc.openInputStream();
You can then use the
InputStream
for reading the file. The
FileConnection
interface has
five methods for obtaining a stream:
DataInputStream openDataInputStream()
DataOutputStream openDataOutputStream()
InputStream openInputStream()
OutputStream openOutputStream()
OutputStream openOutputStream(long Offset)
The second variation of
openOutputStream()
allows you to specify a byte offset to start
writing to the file.
■
Note
The top-level directory of a file system is called the root. Each file system on a device may corre-
spond to a separate flash memory card or storage subsystem, and will have a different root name. The name
of the root is arbitrary and totally device dependent. For example, a vendor may choose to name the root of
an inserted SD memory card “SDCard1/”, while the device's own internal flash file system may have a root
name of “InternalFlash/”. You can obtain an enumeration of all the available roots on a device using the
FileSystemRegistry
, described later in this chapter.
Search WWH ::
Custom Search