⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 recordengine.java

📁 JAVAME Core technology and best practices_mingjava.rar
💻 JAVA
字号:
package com.j2medev.chapter3;

import java.io.*;
import javax.microedition.rms.*;
import java.util.*;

public class RecordEngine {
    
    private RecordStore index = null;
    private RecordStore data = null;
    //初始化RecordEngine的时候,把Index的信息读入到Hashtable中
    private Hashtable buffer = new Hashtable();
    public static final String INDEX = "index";//存储索引
    public static final String DATA = "data";//存储数据
    public boolean isbuffer = true;
    
    class KeyFilter implements RecordFilter {
        
        private String key = "";
        KeyFilter(String key){
            this.key = key;
        }
        public boolean matches(byte[] data){
            String s = new String(data);
            return s.equals(key);
        }
    }
    //在数据RS和索引RS更新的时候,相关方法被回调
    class PictureListener implements RecordListener{
        
        public void recordAdded(RecordStore rs,int recordId){
            if(rs == index){
                try{
                    byte[] b = rs.getRecord(recordId);
                    ByteArrayInputStream bais = new ByteArrayInputStream(b);
                    DataInputStream dis = new DataInputStream(bais);
                    Index i = Index.deserialize(dis);
                    dis.close();
                    buffer.put(i.key,new Integer(i.id));
                    System.out.println(i.key+"is added");
                    i = null;
                }catch(RecordStoreException ex){
                    ex.printStackTrace();
                }catch(IOException ex){
                    ex.printStackTrace();
                }
            }
            //if rs == data does nothing
        }
        
        public void recordChanged(RecordStore rs,int recordId){
        }
        
        public void recordDeleted(RecordStore rs,int recordId){
            if(rs == data){
                Enumeration e = buffer.keys();
                while(e.hasMoreElements()){
                    Object key = e.nextElement();
                    if(buffer.get(key).equals(new Integer(recordId))){
                        buffer.remove(key);
                        System.out.println(key.toString()+"is deleted");
                    }
                }
            }
        }
    }
    
    public RecordEngine(boolean buffer) {
        //打开两个RecordStore
        this.isbuffer = buffer;
        try{
            clearAll();
            data = RecordStore.openRecordStore(INDEX,true);
            index = RecordStore.openRecordStore(DATA,true);
            data.addRecordListener(new PictureListener());
            index.addRecordListener(new PictureListener());
            //写五个Picture
            if(isEmpty()){
                writeData(5);
            }
            if(isbuffer){
                initBuffer();
            }
        }catch(RecordStoreException ex){
            ex.printStackTrace();
        }
    }
    public void clearAll(){
        try{
            data = RecordStore.openRecordStore(INDEX,true);
            index = RecordStore.openRecordStore(DATA,true);
            data.closeRecordStore();
            index.closeRecordStore();
            RecordStore.deleteRecordStore(DATA);
            RecordStore.deleteRecordStore(INDEX);
        }catch(RecordStoreException ex){
            ex.printStackTrace();
        }
    }
    public boolean isEmpty(){
        try{
            int size = data.getNumRecords();
            return (size>0)?false:true;
        }catch(RecordStoreException ex){
            ex.printStackTrace();
        }
        return true;
    }
    
    public void deletePicture(String picName) throws IOException,RecordStoreException{
        //需要同时更新数据RS和索引RS
        int id = ((Integer)buffer.get(picName)).intValue();
        data.deleteRecord(id);
        RecordEnumeration re = index.enumerateRecords(new KeyFilter(picName), null,false);
        if(re.hasNextElement()){
            int i = re.nextRecordId();
            index.deleteRecord(i);
        }
    }
    
    public String addPicture(Picture pic) throws IOException,RecordStoreException{
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        pic.serialize(dos);
        byte[] img = baos.toByteArray();
        int id = data.addRecord(img,0,img.length);
        //重置baos的缓冲区,重复使用
        baos.reset();
        //构造Index,写入索引RS
        Index i = new Index(id,pic.name);
        i.serialize(dos);
        byte[] idx = baos.toByteArray();
        index.addRecord(idx,0,idx.length);
        return pic.name;
    }
    public void writeData(int num){
        //向数据RS中写num个Picture
        InputStream is = getClass().getResourceAsStream("/city.png");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int length = -1;
        //一块一块的读取,而不是一个字节一个字节地读取
        byte[] img = new byte[1024];
        try{
            if(is != null){
                while((length = is.read(img) )!=-1){
                    baos.write(img,0,length);
                }
            }
        }catch(IOException ex){
            ex.printStackTrace();
        }
        byte[] data = baos.toByteArray();
        try{
            for(int i = 0;i<num;i++){
                Picture p = new Picture("pic"+new Date().getTime()+i,data);
                //添加一个Picture
                addPicture(p);
                System.out.println("add picture "+p.name);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    public Picture getPictureByName(String name){
        //这里只考虑缓存索引的情况,否则直接return null
        if(isbuffer){
            int id = ((Integer)buffer.get(name)).intValue();
            System.out.println(id);
            try {
                byte[] pic = data.getRecord(id);
                ByteArrayInputStream bais = new ByteArrayInputStream(pic);
                DataInputStream dis = new DataInputStream(bais);
                Picture p = Picture.deserialize(dis);
                dis.close();
                return p;
            } catch (InvalidRecordIDException ex) {
                ex.printStackTrace();
            } catch (RecordStoreNotOpenException ex) {
                ex.printStackTrace();
            } catch (RecordStoreException ex) {
                ex.printStackTrace();
            } catch(IOException e){
                e.printStackTrace();
            }
        }
        return null;
    }
    
    
    public String[] getAllPictureName(){
        Vector v = new Vector();
        //这里只考虑缓存索引的情况,否则直接return null
        if(isbuffer){
            Enumeration e = buffer.keys();
            while(e.hasMoreElements()){
                String s = (String)e.nextElement();
                v.addElement(s);
            }
            String[] name = new String[v.size()];
            v.copyInto(name);
            //释放Vector
            v.removeAllElements();
            v = null;
            return name;
        }
        return null;
    }
    private void initBuffer(){
        try {
            RecordEnumeration re = index.enumerateRecords(null,null,false);
            int length = re.numRecords();
            if(length == 0){
                return;
            }
            byte[] temp = new byte[20];
            //not ByteArrayInputStream
            BufferedArrayInputStream bais = new BufferedArrayInputStream(temp);
            DataInputStream dis = new DataInputStream(bais);
            while(re.hasNextElement()){
                int id = re.nextRecordId();
                int len = index.getRecordSize(id);
                //如果数据比预先分配的temp大,则重新创建一个
                if(len > temp.length){
                    temp = new byte[len];
                    System.out.println("temp'length is changed to "+temp.length);
                }
                //读取数据到temp中,复用BufferedArrayInputStream
                index.getRecord(id,temp,0);
                bais.resetData(temp);
                Index i = Index.deserialize(dis);
                buffer.put(i.key,new Integer(i.id));
            }
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        }catch(IOException ex){
            ex.printStackTrace();
        }
    }
    
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -