日期:2014-05-20 浏览次数:20726 次
package com.j2medev.chapter4; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import javax.microedition.lcdui.Image; import javax.microedition.rms.*; public class Database { public static final String DATABASE_NAME = "database"; private RecordStore rs = null; private boolean empty = true; public Database() { openDatabase(); } private void openDatabase(){ try{ rs = RecordStore.openRecordStore(DATABASE_NAME,true); if(rs.getNumRecords() > 0){ //记录存储中已经有数据 empty = false; populateDatabase(); }else{ //初始化数据内容,向RecordStore中写入图片和文本 populateDatabase(); } }catch(RecordStoreException e){ e.printStackTrace(); } } //向记录存储中写入图片和文本数据 private void populateDatabase(){ try{ initFile("file.txt"); initFile("JavaPowered.png"); }catch(IOException e){ e.printStackTrace(); }catch(RecordStoreException ex){ ex.printStackTrace(); } } private void initFile(String fileName) throws IOException,RecordStoreException{ InputStream is = this.getClass().getResourceAsStream("/"+fileName); if(is != null){ ByteArrayOutputStream baos = new ByteArrayOutputStream(); //创建缓冲区用于读取数据,如果一个字节一个字节读取效率很低。 byte[] data = new byte[1024]; int ch = 0; while((ch = is.read(data, 0,data.length))!=-1){ baos.write(data, 0, ch); } byte[] array = baos.toByteArray(); //添加记录 rs.addRecord(array, 0, array.length); is.close(); baos.close(); } } public boolean isEmpty(){ return this.empty; } public Image getImage(){ try{ //这里硬编码,我们已知图片记录的recordId是2 byte[] img = rs.getRecord(2); return Image.createImage(img, 0,img.length); }catch(RecordStoreException e){ e.printStackTrace(); } return null; } public String getText(){ try{ //这里硬编码,我们已知文本记录的recordId是1 byte[] text = rs.getRecord(1); //解决中文问题,使用UTF-8编码 return new String(text,"UTF-8" ); }catch(RecordStoreException e){ e.printStackTrace(); }catch(IOException ex){ ex.printStackTrace(); } return null; } }