【Java开源代码栏目提醒】:网学会员在Java开源代码频道为大家收集整理了AddressBookDB.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;
}
}
上一篇:
Address.java
下一篇:
那些令你为之触动的好句子,感慨万分