addressbookdb.java
来自「本光盘是《J2ME无线移动游戏开发》一书的配套光盘」· Java 代码 · 共 106 行
JAVA
106 行
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 + =
减小字号Ctrl + -
显示快捷键?