J2ME开发中数据存储最基本也最常用的方式是RMS存储方式,RMS相关的API所操作的是直接操作对象是byte数组,所以一般在开发过程中我们必须利用封装的思想对应用程序所需存的数据的再封上一层,使其存储数据的接口更好的使用与维护。
在封装的过程中利用流来处理存储的逻辑是最佳的作法,程序逻辑清晰,容易扩展。
对于存数据用到的是ByteArrayOutputStream,DataOutputStream.
对于取数据用到的是ByteArrayInputStream,DataInputStream.
容易的demo是看看wtk中的game工程.
比如:C:/WTK25/apps/Games/src/example/wormgame/WormScore.java
存数据的demo
取数据的demo
上面两个程序段是最普通的写法,没有进一步的封装
(ps:存与取是两个相反的过程,写与读的顺序要统一)
在封装的过程中利用流来处理存储的逻辑是最佳的作法,程序逻辑清晰,容易扩展。
对于存数据用到的是ByteArrayOutputStream,DataOutputStream.
对于取数据用到的是ByteArrayInputStream,DataInputStream.
容易的demo是看看wtk中的game工程.
比如:C:/WTK25/apps/Games/src/example/wormgame/WormScore.java
- try {
- try {
- baos = new ByteArrayOutputStream();
- das = new DataOutputStream(baos);
- das.writeShort((short)newScore);
- das.writeUTF(name);
- data = baos.toByteArray();
- das.close();
- } catch (IOException ioe) {
- throw new RecordStoreException();
- }
- if (myStore == null) {
- openHighScores();
- myStore.setRecord(level + 1, data, 0, data.length);
- closeHighScores();
- } else {
- myStore.setRecord(level + 1, data, 0, data.length);
- }
- } catch (RecordStoreException rse) {
- /* Silently fail; exception to save high score is non-critical */
- }
- /* Read high score store */
- ByteArrayInputStream bais;
- DataInputStream dis;
- byte[] data;
- for (int i = 0; i < WormPit.MAX_LEVELS; i++) {
- data = myStore.getRecord(i + 1);
- if (data != null) {
- try {
- bais = new ByteArrayInputStream(data);
- dis = new DataInputStream(bais);
- highScore[i] = dis.readShort();
- highScoreName[i] = dis.readUTF();
- dis.close();
- } catch (IOException ioe) {
- }
- }
- }
上面两个程序段是最普通的写法,没有进一步的封装
(ps:存与取是两个相反的过程,写与读的顺序要统一)