J2ME 應用使用 JSR-75 (`FileConnection`) 讀寫本地文件時,在 KEmulator 中報 `IOException: openDataInputStream(Unknown Source)`。根因:**模擬器將 `file:///` 根映射到模擬器安裝目錄下的 `file/` 子目錄**,而非系統真實根目錄。
問題重現
// 代碼嘗試讀取 D:/abc.txt
Connector.open("file:///d/abc.txt", Connector.READ); // 拋 IOException
解決方案
- 找到 KEmulator 安裝目錄 (如 `D:\KEmulator\`)。
- 進入 `file\` 子目錄 (`D:\KEmulator\file\`)。
- 建立對應路徑結構:`D:\KEmulator\file\d\abc.txt`。
- 代碼不變,模擬器即可正常讀寫。
原理解析
- KEmulator 為安全隔離,**沙箱化文件系統**,所有 `file:///` 請求重定向到 `/file/`。
- `file:///d/abc.txt` → 映射為 `/file/d/abc.txt`。
- 真機上 `file:///` 映射為手機儲存根目錄 (如 `/sdcard/` 或 `file:///root/`)。
調試技巧
- 用 **Procmon (Process Monitor)** 監控 `KEmulator.exe` 的 `CreateFile/ReadFile` 路徑,即可看到實際訪問的物理路徑。
- 代碼中動態獲取根路徑:`System.getProperty("fileconn.dir.private")` / `fileconn.dir.public` (JSR-75 標準屬性),但模擬器實現不一,建議以相對路徑測試。
遷移建議
J2ME/JSR-75 已淘汰,**現代 Android/iOS 開發請直接使用平台原生文件 API (Context.getFilesDir(), FileProvider, DocumentPicker 等)**,無需模擬器路徑映射煩惱。