操作手機支持文件系統,在應用程序中讀取本地存儲的文件也是必須要掌握的知識。這一篇我做個簡單的示例,從手機存儲上讀取圖片。
由於是通過模擬器來顯示圖片,所以模擬器下的目錄爲root1/photos/,我會在這個目錄底下放幾張圖片。
需要注意一點的是,root1/photos/目錄不一定在wtk的目錄下,雖然在wtk目錄下我能找到,C:/WTK2.5.2/j2mewtk_template/appdb/DefaultColorPhone/filesystem/root1/photos/目錄,但是實驗證明如果文件放在這個目錄下,我無法讀取到。
模擬器中使用的root1/photos/目錄在用戶文件夾下:C:/Users/Sunny/j2mewtk/2.5.2/appdb/DefaultColorPhone/filesystem/root1/photos(Sunny是我的用戶名)
還是先上效果圖來的直接:
在FileSystem類中聲明readImage方法,從文件系統讀取圖片,返回byte[]數組(代碼全部採用LWUIT框架,可以自行改造爲MIDP的代碼)
/** * 讀取圖片 * @param path * @return */ public byte[] readImage(String path) { FileConnection fc = null; try { fc = (FileConnection) Connector.open(path, Connector.READ); InputStream is = fc.openInputStream(); byte[] b = new byte[1024]; int len = 0; ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); while ((len = is.read(b)) != -1) { dos.write(b, 0, len); } byte[] data = baos.toByteArray(); fc.close(); return data; } catch (Exception ex) { ex.printStackTrace(); } return null; }
在root1/photos/下放5張圖片,點擊按鈕讀取圖片,fs是FileSystem類的實例,可以參照前兩節。
public void testReadImageFromEmulator() { String directory = "file:///root1/photos/"; Vector fileVector = fs.getFiles(directory); for (int i = 0; i < fileVector.size(); i++) { String name = fileVector.elementAt(i).toString(); Button b = new Button(directory + name); addComponent(b); b.addActionListener(new ButtonActionListener()); } } class ButtonActionListener implements ActionListener { public void actionPerformed(ActionEvent evt) { Button b = (Button) evt.getSource(); Form f = new Form(); f.setLayout(new BorderLayout()); Image img = getImage(fs.readImage(b.getText())); f.addComponent(BorderLayout.CENTER, new Button(img)); f.addCommand(new Command("返回") { public void actionPerformed(ActionEvent actionevent) { new Favorites(); } }); f.show(); } } public Image getImage(byte[] bytes) { return Image.createImage(bytes, 0, bytes.length); }