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

📄 addressbookdb.java

📁 本光盘是《J2ME无线移动游戏开发》一书的配套光盘
💻 JAVA
字号:
package ch12;

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

public class AddressBookDB {
  private static RecordStore rs = null;
  public AddressBookDB() {
    try {
      rs = RecordStore.openRecordStore("addressbook", false);
      if (rs.getNumRecords() == 0) {
        rs = RecordStore.openRecordStore("addressbook", true);
      }
      else {
        rs.closeRecordStore();
        rs.deleteRecordStore("addressbook");
        rs = RecordStore.openRecordStore("addressbook", true);
      }
    }
    catch (RecordStoreException e) {
      System.out.println(e);
      e.printStackTrace();
    }
  }

//添加一条记录
  public void addAddress(String Name, String Address) {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    DataOutputStream output = new DataOutputStream(os);
    try {
      output.writeUTF(Name + "," + Address);
    }
    catch (IOException e) {
      System.out.println(e);
      e.printStackTrace();
    }
    byte[] b = os.toByteArray();
    try {
      //记录索引从1开始
      int i = rs.addRecord(b, 0, b.length);
      System.out.println(i);
    }
    catch (RecordStoreException e) {
      System.out.println(e);
      e.printStackTrace();
    }
  }

//获取指定记录的姓名部分
  public static String getName(int index) {
    int counter = 1;
    int commalocation = 0;
    String name = null;
    try {
      RecordEnumeration enumRec =
          rs.enumerateRecords(null, null, true);
      while ( (counter <= index) && (enumRec.hasNextElement())) {
        String strTemp = new String(enumRec.nextRecord());
        commalocation = strTemp.indexOf(',');
        name = strTemp.substring(2, commalocation);
        counter++;
      }
    }
    catch (Exception e) {
      System.out.println(e);
      e.printStackTrace();
    }
    return name;
  }

//获取指定记录的地址部分
  public static String getAddress(int index) {
    int counter = 1;
    int commalocation = 0;
    String address = null;
    try {
      RecordEnumeration enumRec =
          rs.enumerateRecords(null, null, false);
      while ( (counter <= index) && (enumRec.hasNextElement())) {
        String strTemp = new String(enumRec.nextRecord());
        commalocation = strTemp.indexOf(',');
        address = strTemp.substring(commalocation + 1);
        counter++;
      }
    }
    catch (Exception e) {
      System.out.println(e);
      e.printStackTrace();
    }
    return address;
  }

//获取记录数
  public static int recordCount() {
    int count = 0;
    try {
      count = rs.getNumRecords();
    }
    catch (Exception e) {
      System.out.println(e);
      e.printStackTrace();
    }
    return count;
  }
}

⌨️ 快捷键说明

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