📄 log.java
字号:
package com.j2medev.chapter3;
import java.util.Date;
import javax.microedition.rms.*;
public class Log {
private RecordStore rs = null;
public static final String LOG_NAME = "log";
public Log() {
//打开RecordStore对象rs
try{
rs = RecordStore.openRecordStore(LOG_NAME,true);
}catch(RecordStoreException ex){
ex.printStackTrace();
//does nothing
}
}
public void closeLog(){
//关闭rs
if(rs != null){
try{
rs.closeRecordStore();
}catch(RecordStoreException ex){
ex.printStackTrace();;
}
}
}
public void clearLog(){
//清除所有rs中的记录
if(rs != null){
try{
rs.closeRecordStore();
RecordStore.deleteRecordStore(LOG_NAME);
}catch(Exception ex){
ex.printStackTrace();
}
}
}
public void log(String message){
//记录方法调用的信息,形式为long:String。其中long代表方法调用时间
String temp = new Date().getTime()+":"+message;
try{
byte[] data = temp.getBytes();
rs.addRecord(data,0,data.length);
}catch(RecordStoreException ex){
ex.printStackTrace();
}
}
public boolean isEmpty(){
//判断rs中是否有数据
try{
int size = rs.getNumRecords();
return (size == 0)?true:false;
}catch(RecordStoreException ex){
ex.printStackTrace();
return true;
}
}
public String[] getLogs(){
//获取所有的记录信息
try{
//按照时间的升序取得记录
RecordEnumeration re = rs.enumerateRecords(null,new MyComparator(),false);
int length = re.numRecords();
if(length == 0){
return null;
}else{
String[] logs = new String[length];
int i = 0;
while(re.hasNextElement()){
//过滤掉字符串前面的long:
byte[] data = re.nextRecord();
String temp = new String(data);
int index = temp.indexOf(":");
logs[i++] = temp.substring(index+1,temp.length());
}
return logs;
}
}catch(RecordStoreException ex){
ex.printStackTrace();
return null;
}
}
//自己定义的RecordComparator,按照时间顺序记录方法的执行先后
private class MyComparator implements RecordComparator{
public int compare(byte[] b1,byte[] b2){
String s1 = new String(b1);
String s2 = new String(b2);
int i1 = s1.indexOf(":");
int i2 = s2.indexOf(":");
if(i1 == -1 || i2 == -1)
return RecordComparator.FOLLOWS;
long l1 = Long.parseLong(s1.substring(0,i1));
long l2 = Long.parseLong(s2.substring(0,i2));
if(l1 > l2){
return RecordComparator.FOLLOWS;
}else if (l1 < l2){
return RecordComparator.PRECEDES;
}else{
return RecordComparator.EQUIVALENT;
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -