j2me版的Preferences
来源:互联网 发布:佰诺网络 编辑:程序博客网 时间:2024/04/29 13:18
- package com.eshore.sweetop.preferences;
- import java.io.ByteArrayInputStream;
- import java.io.ByteArrayOutputStream;
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.IOException;
- import javax.microedition.rms.RecordEnumeration;
- import javax.microedition.rms.RecordStore;
- import javax.microedition.rms.RecordStoreException;
- import javax.microedition.rms.RecordStoreFullException;
- import javax.microedition.rms.RecordStoreNotFoundException;
- import javax.microedition.rms.RecordStoreNotOpenException;
- public class Preferences {
- private Class c;
- private RecordStore rs;
- public Preferences(Class c) {
- this.c = c;
- try {
- rs = RecordStore.openRecordStore(c.getName(), true);
- } catch (RecordStoreFullException e) {
-
- e.printStackTrace();
- } catch (RecordStoreNotFoundException e) {
-
- e.printStackTrace();
- } catch (RecordStoreException e) {
-
- e.printStackTrace();
- }
- }
- public static Preferences userNode(Class c) {
- return new Preferences(c);
- }
- public void put(String key, String value) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- DataOutputStream dos = new DataOutputStream(baos);
- try {
- dos.writeUTF(key);
- dos.writeUTF(value);
- baos.close();
- dos.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- byte[] b = baos.toByteArray();
- try {
- int id=id(key);
- if(id==-1){
- rs.addRecord(b, 0, b.length);
- }else{
- rs.setRecord(id, b, 0, b.length);
- }
- } catch (RecordStoreNotOpenException e) {
- e.printStackTrace();
- } catch (RecordStoreFullException e) {
- e.printStackTrace();
- } catch (RecordStoreException e) {
- e.printStackTrace();
- }
- }
- public String get(String key) {
- RecordEnumeration re = null;
- try {
- re = rs.enumerateRecords(null, null, false);
- while (re.hasNextElement()) {
- byte[] b = re.nextRecord();
- ByteArrayInputStream bais = new ByteArrayInputStream(b);
- DataInputStream dis = new DataInputStream(bais);
- String k = dis.readUTF();
- if (key.equals(k)) {
- return dis.readUTF();
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (re != null) {
- re.destroy();
- }
- }
- return null;
- }
-
- private int id(String key) {
- RecordEnumeration re = null;
- try {
- re = rs.enumerateRecords(null, null, false);
- while (re.hasNextElement()) {
- int id=re.nextRecordId();
- byte[] b = rs.getRecord(id);
- ByteArrayInputStream bais = new ByteArrayInputStream(b);
- DataInputStream dis = new DataInputStream(bais);
- String k = dis.readUTF();
- if (key.equals(k)) {
- return id;
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (re != null) {
- re.destroy();
- }
- }
- return -1;
- }
-
- public void dispose(){
- try {
- rs.closeRecordStore();
- } catch (RecordStoreNotOpenException e) {
-
- e.printStackTrace();
- } catch (RecordStoreException e) {
-
- e.printStackTrace();
- }
- }
- }