menu

秋梦无痕

一场秋雨无梦痕,春夜清风冻煞人。冬来冷水寒似铁,夏至京北蟑满城。

Avatar

FileConnection(FC)

FC api是JSR 75, PDA Optional Packages for the J2ME Platform的一部分,用于访问本地文件系统。

FC api通过Generic Connection Framework(GCF)访问文件系统,允许访问包括存储卡在内的文件系统。

包括如下两个接口和三个类:
FileConnection 访问文件和文件夹的接口。
FileSystemListener 添加删除根目录文件系统的状态监听的接口。
FileSystemRegistry 添加删除根目录文件系统的接口注册类。

ConnectionClosedException 当一个文件句柄的操作被调用,而文件已经被关闭时抛出的异常。
IllegalModeException 当操作所对应的模式不被文件打开模式支持时抛出的异常。

判断是否支持FC:

if(System.getProperty("microedition.io.file.FileConnection.version") != null){ // file.separator
// FCOP available
} else {
// FCOP not available
}

打开文件:

// 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:/");
// / File:
Connection fc = (FileConnection) Connector.open("file:////");

只读方式打开一个文件:

String url = "file:///data.txt";
InputConnection conn = null;
int mode = Connector.READ_ONLY;

try {
conn =(InputConnection) Connector.open( url, mode );
// Always check whether the file or directory exists.
// Create the file if it doesn't exist.
if(!conn.exists()) {
}
} catch( IOException ioe ){
// no file
}

创建一个文件:

String url = "file:///SDCard/data.txt";
FileConnection conn = null;
int mode = Connector.WRITE_ONLY;
try {
conn = (FileConnection)Connector.open(url, mode);
if(filecon.create()){ // create the file
OutputStream out = conn.openOutputStream();
// now write data to the file
}
conn.close();
} catch(IOException e){
// error
} catch(SecurityException e){
// no permission to create/write
}

列举一个目录下的文件:

// FileConnection.list(String filter, boolean includeHidden)
String url = "file:///C:/";
FileConnection conn = null;
try {
conn = (FileConnection) Connector.open(url);
if( conn.isDirectory() ) {
Enumeration names = conn.list();
while( names.hasMoreElements() ){
String name = (String) e.nextElement();
// do something
}
} else {
// not a directory!
}
} catch(IOException e) {
// could not access the URL
} catch(SecurityException e) {
// no permission to read the directory
}

读取文件内容:

String url = "file:///CFCard/data.txt";
InputConnection conn = null;
int mode = Connector.READ_ONLY;

try {
FileConnection fc = (FileConnection)Connector.open(url, mode);
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) {
}


评论已关闭