Summary of Android data persistence tools

Source: Internet
Author: User

Summary of Android data persistence tools

Programmers are the lazy creature and never duplicate the wheel during development. In actual development, data eating is a problem that must be solved, I will summarize several tool classes in addition to processing sqlite, because sqlite Can Use orm directly, and persistent data can be stored in I/O, SharedPreference, and other methods.

External Storage card

Package cn.edu. zafu. utils; import java. io. file; import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. fileOutputStream; import java. io. IOException; import java. io. unsupportedEncodingException; import android. OS. environment;/*** external memory card tool class * requires permission to be added * android. permission. WRITE_EXTERNAL_STORAGE * android. permission. MOUNT_UNMOUNT_FILESYSTEMS ** @ author lizhangqu * @ version 1.0 * */Public class ExternalStorageUtil {/*** whether to write ** @ return writability */public static boolean isExternalStorageWritable () {String state = Environment. getExternalStorageState (); if (Environment. MEDIA_MOUNTED.equals (state) {return true;} return false;}/*** readable ** @ return readability */public static boolean isExternalStorageReadable () {String state = Environment. getExternalStorageState (); if (Environment. MEDIA_MOU NTED. equals (state) | Environment. MEDIA_MOUNTED_READ_ONLY.equals (state) {return true;} return false;}/*** obtain the root path ** @ return external memory card root path */public static String getExternalStoragePath () {if (isExternalStorageWritable () return Environment. getExternalStorageDirectory (). getAbsolutePath (); elsereturn null;}/*** get the download directory path ** @ return external memory card download path */public static String getExternalDownloadPath () {return Environm Ent. getExternalStoragePublicDirectory (Environment. DIRECTORY_DOWNLOADS ). getAbsolutePath ();} /*** write the file to the root path ** @ param fileName file name * @ param content Context * @ return indicates whether the file is successfully written */public static boolean write (String fileName, String content) {return write ("/", fileName, content );} /*** write byte to the root directory ** @ param fileName file name * @ param bytes file byte array * @ return write successful */public static boolean writeBytes (String fileName, byt E [] bytes) {return writeBytes ("/", fileName, bytes);}/*** write a string to the file in the specified directory, the path starts with/and ends with ** @ param path: the path relative to the root path. The path starts, end with/* @ param fileName file name * @ param content File content * @ return write successful */public static boolean write (String path, String fileName, String content) {return writeBytes (path, fileName, content. getBytes ();}/*** write a byte array to the file in the specified directory. The path starts/ends with/** @ param path relative to the root path, path starts with/and ends with/* @ param fileNam E file name * @ param bytes byte array * @ return */public static boolean writeBytes (String path, String fileName, byte bytes []) {boolean flag = false; if (! Path. equals ("/") {File dir = new File (getExternalStoragePath () + path); if (! Dir. exists () {if (! (Dir. mkdir () | dir. isDirectory () {// File directory creation failed or not a directory return false; }}} file File = new File (getExternalStoragePath () + path + fileName ); fileOutputStream fos = null; try {fos = new FileOutputStream (file, false); fos. write (bytes); flag = true;} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} finally {if (fos! = Null) {try {fos. close ();} catch (IOException e) {e. printStackTrace () ;}} return flag ;} /*** read byte from the root path ** @ param fileName file name * @ return byte array */public static byte [] readBytes (String fileName) {return readBytes ("/", fileName);}/*** read bytes from the specified directory. The path starts with/and ends with ** @ param path relative to the root path. The path starts, end with/* @ param fileName File name * @ return byte array */public static byte [] readBytes (String path, String fileName) {file File file = n Ew File (getExternalStoragePath () + path + fileName); if (! File. isFile () {return null;} else {FileInputStream FD = null; try {fiis = new FileInputStream (file); int length = fiis. available (); byte [] buffer = new byte [length]; FCM. read (buffer); return buffer;} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} finally {if (FS! = Null) {try {FS. close ();} catch (IOException e) {e. printStackTrace () ;}} return null ;}} /*** read text from the root directory ** @ param fileName file name * @ return String */public static String read (String fileName) {return read ("/", fileName);}/*** read text from the specified directory. The path starts with/and ends with ** @ param path relative to the root path. The path starts, end with/* @ param fileName file name * @ return String */public static String read (String path, String fileName) {try {byte [] readBytes = readBytes (path, fileName ); if (readBytes = null) {return null;} return new String (readBytes, "UTF-8");} catch (UnsupportedEncodingException e) {e. printStackTrace ();} return null;}/*** delete from the root directory ** @ param fileName file name * @ return delete successful */public static boolean delete (String fileName) {return delete ("/", fileName);}/*** delete from the specified directory. The path starts/ends with/** @ param path relative to the root path, path starts with/and ends with/* @ param fileName file name * @ return: whether the deletion is successful */public static boolean delete (String path, String fileName) {File file = new File (getExternalStoragePath () + path + fileName); if (file. exists () return file. delete (); elsereturn true ;}}

Built-in storage card

Package cn.edu. zafu. utils; import java. io. file; import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. fileOutputStream; import java. io. IOException; import java. io. unsupportedEncodingException; import android. content. context; /*** internal memory card tool class ** @ author lizhangqu * @ version 1.0 */public class InternalStorageUtil {/*** Append content after the original file ** @ param context * @ param fileName file name * @ p The text appended by aram content * @ return whether the append is successful */public static boolean append (Context context, String fileName, String content) {return writeBytes (context, fileName, content. getBytes (), true);}/*** write to the file, if a file exists, it overwrites the ** @ param context Context * @ param fileName file name * @ param content written text * @ return whether the file is successfully written */public static boolean write (context, string fileName, String content) {return writeBytes (context, fileNam E, content. getBytes (), false );} /***** write byte ** @ param context Context * @ param fileName file name * @ param content write byte * @ return write successful */public static boolean writeBytes (context, string fileName, byte [] content) {return writeBytes (context, fileName, content, false);}/*** write to the file, when a file exists, determine whether to overwrite the ** @ param context * @ param fileName file name * @ param content written byte * @ param isAppend whether to append * @ retur N whether the write is successful */public static boolean writeBytes (Context context, String fileName, byte [] content, boolean isAppend) {FileOutputStream fout = null; boolean flag = false; try {if (isAppend) {fout = context. openFileOutput (fileName, Context. MODE_APPEND);} else {fout = context. openFileOutput (fileName, Context. MODE_PRIVATE);} fout. write (content); flag = true;} catch (FileNotFoundException e) {e. printStackTrace () ;} Catch (IOException e) {e. printStackTrace ();} finally {try {if (fout! = Null) {fout. close (); fout = null ;}} catch (IOException e) {e. printStackTrace () ;}} return flag ;} /*** read File ** @ param context Context * @ param fileName file name * @ return file content String */public static String read (context, String fileName) {byte [] buffer = readBytes (context, fileName); String result = null; try {result = new String (buffer, "UTF-8");} catch (UnsupportedEncodingException e) {e. printStackTrace ();} Return result;}/*** @ param context Context * @ param fileName file name * @ return byte array */public static byte [] readBytes (context, String fileName) {FileInputStream fin = null; byte [] buffer = null; try {fin = context. openFileInput (fileName); int length = fin. available (); buffer = new byte [length]; fin. read (buffer);} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. printStac KTrace ();} finally {try {if (fin! = Null) {fin. close (); fin = null ;}} catch (IOException e) {e. printStackTrace () ;}} return buffer;}/*** clear all files, if a file is not cleared, false is returned ** @ param context Context * @ return: whether the file is clear */public static boolean clear (context) {boolean flag = true; string [] files = context. fileList (); for (String fileName: files) {boolean result = context. deleteFile (fileName); if (result = false) {flag = false ;}} return flag ;} /*** clear the file by file name ** @ param context Context * @ param fileName file name * @ return whether the file is successfully deleted */public static boolean delete (context, String fileName) {return context. deleteFile (fileName);}/*** returns the absolute path of the internal storage ** @ param context Context * @ return app built-in folder path */public static String getFileDir (context) {File filesDir = context. getFilesDir (); return filesDir. getAbsolutePath ();}}
Read resource files

Package cn.edu. zafu. utils; import java. io. IOException; import java. io. inputStream; import java. io. unsupportedEncodingException; import android. content. context; /*** read assert resources ** @ author lizhangqu * @ version 1.0 */public class ResouceFileUtil {/*** read text resources from the assert folder ** @ param context * @ param fileName file name * @ return file content String */public static String readStringFromAssert (Context context, string file Name) {String result = null; byte [] buffer = readBytesFromAssert (context, fileName); try {result = new String (buffer, "UTF-8");} catch (UnsupportedEncodingException e) {e. printStackTrace ();} return result ;} /*** read text resources from the raw folder ** @ param context Context * @ param rawId raw resource id * @ return file content String */public static String readStringFromRaw (context, int rawId) {String result = null; byte [] buffer = readB YtesFromRaw (context, rawId); try {result = new String (buffer, "UTF-8");} catch (UnsupportedEncodingException e) {e. printStackTrace ();} return result ;} /*** read the file from the assert folder to the byte array ** @ param context Context * @ param fileName file name * @ return file byte array */public static byte [] readBytesFromAssert (context context, string fileName) {InputStream is = null; byte [] buffer = null; try {is = context. getAssets (). open (fileNam E); int size = is. available (); buffer = new byte [size]; is. read (buffer);} catch (IOException e) {e. printStackTrace ();} finally {if (is! = Null) {try {is. close (); is = null;} catch (IOException e) {e. printStackTrace () ;}} return buffer ;} /*** read the file from the raw folder to the byte array ** @ param context * @ param rawId raw resource id * @ return file byte array */public static byte [] readBytesFromRaw (Context context, int rawId) {InputStream is = null; byte [] buffer = null; try {is = context. getResources (). openRawResource (rawId); int size = is. available (); buffer = new byte [size ]; Is. read (buffer);} catch (IOException e) {e. printStackTrace ();} finally {if (is! = Null) {try {is. close (); is = null;} catch (IOException e) {e. printStackTrace () ;}} return buffer ;}}


SharedPreference operation

Package cn.edu. zafu. utils; import android. content. context; import android. content. sharedPreferences; /*** tool class for persistent data in SharedPreference mode ** @ author lizhangqu * @ version 1.0 */public class SharedPreferenceUtil {/*** Save the key-Value Pair ** @ param context * @ param fileName file name * @ param key * @ param value * @ return whether the file is saved successfully */public static boolean set (Context context, string fileName, String key, String value) {SharedPreferences sharedPreferences = context. getSharedPreferences (fileName, Context. MODE_PRIVATE); SharedPreferences. editor editor = sharedPreferences. edit (); editor. putString (key, value); return editor. commit ();}/*** get the key value, if not, return "" ** @ param context * @ param fileName file name * @ param key * @ return value, if not, "" */public static String get (Context context, String fileName, String key) {return get (context, fileName, key, "");} is returned ,"");} /*** get the value corresponding to the key, if not, return defaultValue ** @ param context * @ param fileName file name * @ param key * @ param defaultValue default * @ return value, if no value exists, ultvalue */public static String get (Context context, String fileName, String key, String defaultValue) {SharedPreferences sharedPreferences = context. getSharedPreferences (fileName, Context. MODE_PRIVATE); String value = sharedPreferences. getString (key, defaultValue); // The second parameter is the default value return value ;} /*** remove an item * @ param context Context * @ param fileName file name * @ param key * @ return whether the file is successfully removed */public static boolean remove (context, String fileName, string key) {SharedPreferences sharedPreferences = context. getSharedPreferences (fileName, Context. MODE_PRIVATE); SharedPreferences. editor editor = sharedPreferences. edit (); editor. remove (key); return editor. commit ();}/*** clear file content * @ param context Context * @ param fileName file name * @ return whether the file is cleared successfully */public static boolean clear (context, string fileName) {SharedPreferences sharedPreferences = context. getSharedPreferences (fileName, Context. MODE_PRIVATE); SharedPreferences. editor editor = sharedPreferences. edit (); editor. clear (); return editor. commit ();} /*** whether a certain item exists * @ param context * @ param fileName file name * @ param key * @ return whether the value corresponding to this key exists */public static boolean contatins (context context, string fileName, String key) {SharedPreferences sharedPreferences = context. getSharedPreferences (fileName, Context. MODE_PRIVATE); return sharedPreferences. contains (key );}}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.