?? database.java
字號(hào):
package com.j2medev.chapter4;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import javax.microedition.lcdui.Image;
import javax.microedition.rms.*;
public class Database {
public static final String DATABASE_NAME = "database";
private RecordStore rs = null;
private boolean empty = true;
public Database() {
openDatabase();
}
private void openDatabase(){
try{
rs = RecordStore.openRecordStore(DATABASE_NAME,true);
if(rs.getNumRecords() > 0){
//記錄存儲(chǔ)中已經(jīng)有數(shù)據(jù)
empty = false;
}else{
//初始化數(shù)據(jù)內(nèi)容,向RecordStore中寫(xiě)入圖片和文本
populateDatabase();
}
}catch(RecordStoreException e){
e.printStackTrace();
}
}
//向記錄存儲(chǔ)中寫(xiě)入圖片和文本數(shù)據(jù)
private void populateDatabase(){
try{
initFile("file.txt");
initFile("JavaPowered.png");
}catch(IOException e){
e.printStackTrace();
}catch(RecordStoreException ex){
ex.printStackTrace();
}
}
private void initFile(String fileName) throws IOException,RecordStoreException{
InputStream is = this.getClass().getResourceAsStream("/"+fileName);
if(is != null){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//創(chuàng)建緩沖區(qū)用于讀取數(shù)據(jù),如果一個(gè)字節(jié)一個(gè)字節(jié)讀取效率很低。
byte[] data = new byte[1024];
int ch = 0;
while((ch = is.read(data, 0,data.length))!=-1){
baos.write(data, 0, ch);
}
byte[] array = baos.toByteArray();
//添加記錄
rs.addRecord(array, 0, array.length);
is.close();
baos.close();
}
}
public boolean isEmpty(){
return this.empty;
}
public Image getImage(){
try{
//這里硬編碼,我們已知圖片記錄的recordId是2
byte[] img = rs.getRecord(2);
return Image.createImage(img, 0,img.length);
}catch(RecordStoreException e){
e.printStackTrace();
}
return null;
}
public String getText(){
try{
//這里硬編碼,我們已知文本記錄的recordId是1
byte[] text = rs.getRecord(1);
//解決中文問(wèn)題,使用UTF-8編碼
return new String(text,"UTF-8" );
}catch(RecordStoreException e){
e.printStackTrace();
}catch(IOException ex){
ex.printStackTrace();
}
return null;
}
}
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -