兩個小時精通Android開發之數據持久存儲篇

兩個小時精通Android開發之數據持久存儲篇

 

作者:孫東風 2010-01-15(轉載務必註明出處)

 

筆者在前面的兩篇文章《兩個小時精通Android開發之界面篇》、《兩個小時精通Android開發之按鍵映射篇》分別講了無縫移植J2ME程序到Android平臺上對界面和用戶按鍵交互所做的適配接口,原則上利用這些接口原有的J2ME程序基本不用做任何的修改就可以運行在Android平臺上,所以精通J2ME也就等於精通了Android

 

筆者這篇文章裏要講述的是J2ME平臺和Android平臺另外一個重要的不同點,那就是數據持久存儲系統。

 

J2ME平臺裏採用RMS系統進行數據的持久存儲,而Android平臺則提供了豐富的接口進行數據的持久存儲,但任何持久存儲的本質無非就是數據串行化後被保存到磁盤空間上,仔細研究J2ME平臺RMS系統的實現源碼可以看到,J2ME是通過一個叫做RecordStoreFile的類進行數據持久化存儲的,而這個RecordStoreFile類的實現如下:

 

public class RecordStoreFile {

   private static SecurityToken classSecurityToken;

    private static final String dbExtension = ".db";

    private RandomAccessStream recordStream;

    private String myStoragePath;

 

    public static void initSecurityToken(SecurityToken token) {

    if (classSecurityToken != null) {

        return;

    }

    classSecurityToken = token;

    }

 

    public RecordStoreFile(String uidPath)

    throws IOException

    {

    RandomAccessStream newStream;

    myStoragePath = uidPath;

 

    newStream = new RandomAccessStream(classSecurityToken);

    newStream.connect(myStoragePath, Connector.READ_WRITE);

    recordStream = newStream;

    }

 

    public static String getUniqueIdPath(String fileName) {

    return getStoragePath(fileName);

    }

   

    public static String getUniqueIdPath(String vendorName, String suiteName,

                     String fileName) {

    return getStoragePath(vendorName, suiteName, fileName);

    }

 

    public static boolean exists(String uidPath) {

    File file;

    file = new File(classSecurityToken);

    return file.exists(uidPath);

    }

 

   

    public static boolean deleteFile(String uidPath)

    {

    File file;

    file = new File(classSecurityToken);

    try {

        file.delete(uidPath);

        return true;

    } catch (IOException ioe) {

        return false;

    }

    }

   

    public void seek(int pos) throws IOException

    {

    recordStream.setPosition(pos);

    }

 

    public void write(byte[] buf) throws IOException

    {

    write(buf, 0, buf.length);

    }

 

    public void write(byte[] buf, int offset, int numBytes) throws IOException

    {

    recordStream.writeBytes(buf, offset, numBytes);

    }

   

    public int read(byte[] buf) throws IOException

    {

    return read(buf, 0, buf.length);

    }

 

    public int read(byte[] buf, int offset, int numBytes) throws IOException

    {

    return recordStream.readBytes(buf, offset, numBytes);

    }

 

    public void close() throws IOException

    {

    // close recordStream if it exists

    if (recordStream != null) {

        recordStream.disconnect();

        recordStream = null;

    }

    }

 

    public void truncate(int size) throws IOException

    {

    if (recordStream != null) {   

        recordStream.truncate(size);

    }   

    }

 

    public static String[] listRecordStores() {

        return listRecordStoresForSuite(new File(classSecurityToken),

            getStoragePath(null), false);

    }

 

    private static String[] listRecordStoresForSuite(File storage,

                                                     String suiteStorageRoot,

                                                     boolean rawNames) {

    Vector files;

    Vector names;

    String file;

    String asciiName;

   

    files = storage.filenamesThatStartWith(suiteStorageRoot);

    names = new Vector();

   

    // work through list of strings from the directory

    for (int i = 0; i < files.size(); i++) {

        file = (String)files.elementAt(i);

        if (file.endsWith(dbExtension)) {

                if (rawNames) {

                    names.addElement(file);

                } else {

                    asciiName = file.substring(suiteStorageRoot.length(),

                       file.length() - 3);

                    names.addElement(File.asciiFilenameToUnicode(asciiName));

                }

        }

    }

 

    if (names.size() == 0) {

        return null;

    }

   

    String[] rv = new String[names.size()];

    names.copyInto(rv);

    return rv;

    }

   

    public static void removeRecordStoresForSuite(SecurityToken token,

            String suiteStorageRoot) {

 

        File storage;

    String[] filenames;

   

    storage = new File(token);

        filenames = listRecordStoresForSuite(storage, suiteStorageRoot, true);

        if (filenames == null) {

            return;

        }

 

        for (int i = 0; i < filenames.length; i++) {

            try {

                storage.delete(filenames[i]);

            } catch (IOException ioe) {

                // move on to the next suite

            }

        }

    }

   

    public static boolean suiteHasRmsData(String suiteStorageRoot) {

    File storage = new File(classSecurityToken);

    Vector files = storage.filenamesThatStartWith(suiteStorageRoot);

 

    for (int i = 0; i < files.size(); i++) {

        String file = (String)files.elementAt(i);

        if (file.endsWith(dbExtension)) {

                return true;

            }

        }

 

        return false;

    }

 

    public static int spaceAvailable()

    {

    return new File(classSecurityToken).getBytesAvailableForFiles();

    }

 

    private static String getStoragePath(String name)

    {

    String str;

    MIDletSuite mSuite;

    StringBuffer path;

   

    mSuite = Scheduler.getScheduler().getMIDletSuite();

   

    str = mSuite.getStorageRoot();

    if (name != null) {

        path = new StringBuffer(str);

        // convert the unicode filename into a system acceptable string

        path.append(File.unicodeToAsciiFilename(name));

        path.append(dbExtension);

        str = path.toString();

    }

    return str;

    }

    private static String getStoragePath(String vendor, String suite,

                     String name) {

    String str = File.getStorageRoot();

    StringBuffer path = new StringBuffer(str);

    if (vendor != null && suite != null) {

        path.append(File.unicodeToAsciiFilename(vendor));

        path.append('_');

        path.append(File.unicodeToAsciiFilename(suite));

        path.append('_');

    }

    if (name != null) {

        path.append(File.unicodeToAsciiFilename(name));

        path.append(dbExtension);

        str = path.toString();

    }

    return str;

    }

}

 

可見,RMS系統也是通過IO把數據串行化後存儲應用程序的空間內的,絕大多數的J2ME程序都需要利用RMS來進行數據的持久存儲的,比如遊戲積分、系統設置等。那麼爲了無縫移植J2MEAndroid平臺,筆者自己寫了一個簡易的RMS系統,能滿足絕大多數應用程序的需要。

 

Android下對文件的操作和J2ME基本一樣,但是需要綁定一個Context上下文,以把文件保存到當前應用程序的目錄下,這個目錄在打開DDMS窗口後可以看到,具體位置是data/data/PACKAGE_NAME/files下面。

 

利用文件操作可以進行數據的讀寫,筆者封裝的接口如下:

 

    public static boolean deleteFile(String fileName){     

        File file = new File(fileName);      

        if(file.isFile() && file.exists()){     

            file.delete();     

            System.out.println("刪除單個文件"+fileName+"成功!");     

            return true;     

        }else{     

            System.out.println("刪除單個文件"+fileName+"失敗!");     

            return false;     

        }     

    }     

 

     public String read(String file) {

         String data = "";

         try {

              FileInputStream stream = System.getSystemHandler().getContext().openFileInput(file);

              StringBuffer sb = new StringBuffer();

              int c;

              while ((c = stream.read()) != -1) {

                   sb.append((char) c);

              }

              stream.close();

              data = sb.toString();

 

         } catch (FileNotFoundException e) {

              e.printStackTrace();

         } catch (IOException e) {

              e.printStackTrace();

         }

         return data;

     }

 

     public void write(String file, byte[] msg) {

         try {

              FileOutputStream stream = System.getSystemHandler().getContext().openFileOutput(file,Context.MODE_WORLD_WRITEABLE);

              stream.write(msg);

              stream.flush();

              stream.close();

         } catch (FileNotFoundException e) {

              e.printStackTrace();

         } catch (IOException e) {

              e.printStackTrace();

         }

     }

 

有了基本的讀寫數據操作,就可以封裝RMS中常見的key-value的保存和讀取了,代碼實現如下:

 

public boolean put(String key, byte[] value) {

         boolean bSaveOk = false;

         byte[] data = null;

         if (value == null) {

              throw new NullPointerException();

         }

         ByteArrayOutputStream bout = null;

         DataOutputStream dout = null;

         try {

              bout = new ByteArrayOutputStream();

              dout = new DataOutputStream(bout);

              dout.writeUTF(key);

              dout.writeInt(value.length);

              dout.write(value, 0, value.length);

              data = bout.toByteArray();

 

              write(dbName,data);        

              bSaveOk = true;

         } catch (Exception e) {

              bSaveOk = false;

              e.printStackTrace();

         }

        

         return bSaveOk;

     }

 

     public byte[] getByteArray(String key) {

         ByteArrayInputStream bin = null;

         DataInputStream din = null;

         byte[] data = null;       

         try {

                   String valueKey = read(dbName);

                   din = new DataInputStream(new ByteArrayInputStream(valueKey.getBytes()));

 

                   while(din.available() > 0)

                   {

                       String getKey = din.readUTF();

                       int getLength = din.readInt();

    

                       data = new byte[getLength];

                       int bytesRead = 0;

                       while (bytesRead < data.length) {

                            int count = din.read(data, bytesRead, data.length

                                     - bytesRead);

                            if (count == -1)

                                 break;

                            bytesRead += count;

                       }

                      

                       if(getKey.equals(key))

                            break;

                   }

                                

                   din.close();

                   din = null;

         } catch (Exception e) {

              e.printStackTrace();

              data = null;

         }

         return data;

     }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章