📄 recordstoremidlet.java
字号:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import java.io.*;
public class RecordStoreMIDlet extends MIDlet {
private RecordStore rs;
private String name;//玩家的姓名
private int record;//玩家的得分
private Display display;
public RecordStoreMIDlet() {
super();
display = Display.getDisplay(this);
}
protected void startApp() throws MIDletStateChangeException {
record = 5000;//假设玩家本次得分是100分
name = "playName";//玩家的姓名是"playName"
String dbname = "dbName";
Form f = new Form("RS Test");
rs = openRSAnyway(dbname);
if (rs == null) {
f.append("Table open fail");
} else {
try {
if (rs.getNextRecordID() == 1) {//如果rs中没有记录就增加一条数据
add("player1", 80);
f.append("rs中没有数据,增加本次的数据");
} else {
if (matches()) {
if (save(name, record)) {
f.append("本次修改数据成功!\n");
f.append("修改数据为:\n");
f.append("玩家姓名:" + name + "\n");
f.append("得分是:" + record);
}
} else {
f.append("本次得分为" + record + "\n");
f.append("小于数据库中的分数,不覆盖rs中的数据");
}
}
rs.closeRecordStore();
} catch (Exception e) {
}
}
display.setCurrent(f);
}
protected void pauseApp() {
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
}
public RecordStore openRSAnyway(String rsname) {
RecordStore rs = null;
// 名稱大於32 個字元就不接受
if (rsname.length() > 32)
return null;
try {
rs = RecordStore.openRecordStore(rsname, true);
return rs;
} catch (Exception e) {
return null;
}
}
public boolean add(String playerName, int score) {//在rs中增加一条记录
boolean ok = false;
ByteArrayOutputStream bo = new ByteArrayOutputStream();
DataOutputStream doSteam = new DataOutputStream(bo);
try {
doSteam.writeUTF(playerName);
doSteam.writeInt(score);
byte data[] = bo.toByteArray();
rs.addRecord(data, 0, data.length);
doSteam.close();
ok = true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
ok = false;
}
return ok;
}
public boolean matches() {//用本次玩家的分数和rs中的数据作比较
boolean ok = false;
try {
byte[] data = rs.getRecord(1);
DataInputStream doSteam = new DataInputStream(
new ByteArrayInputStream(data));
String theName = doSteam.readUTF();
int theRecord = doSteam.readInt();
if (theRecord < record)
ok = true;
doSteam.close();
} catch (Exception e) {
e.printStackTrace();
ok = false;
}
return ok;
}
public boolean save(String playerName, int score) {//在rs中保存本次数据
boolean ok = false;
ByteArrayOutputStream bo = new ByteArrayOutputStream();
DataOutputStream doSteam = new DataOutputStream(bo);
try {
doSteam.writeUTF(playerName);
doSteam.writeInt(score);
byte data[] = bo.toByteArray();
rs.setRecord(1, data, 0, data.length);
doSteam.close();
ok = true;
} catch (Exception e) {
ok = false;
// TODO Auto-generated catch block
e.printStackTrace();
}
return ok;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -