JSR-75 分為 File (本地檔案系統) 與 PIM (個人資訊管理) 兩部分。本文聚焦 File 部分,提供四個開箱即用的工具方法:目錄列舉、檔案儲存、刪除、讀取。
/**
* 取得指定路徑下的所有檔案與子目錄名稱
* @param path 目錄 URL,必須以 '/' 結尾,如 "file:///c:/pictures/"
* @return Vector 檔名/目錄名列表,失敗返回 null
*/
public Vector list(String path) {
try {
FileConnection fc = (FileConnection) Connector.open(path);
if (!fc.exists()) return null;
Vector listVec = new Vector(0, 1);
Enumeration en = fc.list(); // 返回項目名,目錄以 '/' 結尾
while (en.hasMoreElements()) {
listVec.addElement((String) en.nextElement());
}
return listVec;
} catch (Exception e) {
System.out.println("listErr: " + e);
return null;
}
}
關鍵點:目錄路徑尾碼 / 不可省略,否則 list() 返回空。
/**
* 將位元組陣列儲存為檔案
* @param path 完整檔案 URL,如 "file:///e:/data.bin"
* @param fileData 任意二進位內容 (圖片、音訊、文字等)
*/
public void saveFile(String path, byte[] fileData) {
try {
FileConnection fc = (FileConnection) Connector.open(path);
fc.create(); // 不存在則建立檔案
fc.setWritable(true);
OutputStream os = fc.openOutputStream();
os.write(fileData);
os.close();
fc.close();
} catch (Exception e) {
System.out.println("saveFileErr: " + e);
}
}
/**
* 刪除指定檔案或空目錄
* @param path 目標 URL
*/
public void deleteFile(String path) {
try {
FileConnection fc = (FileConnection) Connector.open(path);
if (fc.exists()) fc.delete();
fc.close();
} catch (Exception e) {
System.out.println("deleteFileErr: " + e);
}
}
/**
* 讀取檔案全部內容至位元組陣列
* @param path 檔案 URL
* @return 位元組陣列,失敗或不存在返回 null
*/
public byte[] readFile(String path) {
try {
FileConnection fc = (FileConnection) Connector.open(path);
if (!fc.exists()) return null;
InputStream is = fc.openInputStream();
byte[] buffer = new byte[is.available()];
is.read(buffer);
is.close();
fc.close();
return buffer;
} catch (Exception e) {
System.out.println("readFileErr: " + path + e);
return null;
}
}
is.available() 分配超大記憶體這四個方法構成了 J2ME 檔案操作的基礎工具箱,靈活組合即可滿足多數應用的本地存儲需求。