Overview of the Android Data Persistence tool class

Source: Internet
Author: User

Program Ape is the most lazy creatures, in the development of never repeat the wheel, the actual development of data eating is inevitable to deal with a problem, first summed up a few in addition to processing sqlite several tools, because SQLite can directly use ORM, persistent data has I/O, Sharedpreference and so on.

External memory 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 storage card Tool class * need to add permission * Android.permission.WRITE_EXTERNAL_STORAGE * android.permission.MOUNT_ Unmount_filesystems * * @author Lizhangqu * @version 1.0 * */public class Externalstorageutil {/** * is writable * * @return Available Write Sex */public static Boolean isexternalstoragewritable () {String state = Environment.getexternalstoragestate (); Environment.MEDIA_MOUNTED.equals (state)) {return true;} return false;} /** * is readable * * @return readability */public static Boolean isexternalstoragereadable () {String state = Environment.getexternalsto Ragestate (); if (Environment.MEDIA_MOUNTED.equals (state) | | Environment.MEDIA_MOUNTED_READ_ONLY.equals (state)) {return true;} return false;} /** * Get Root Path * * @return external memory card root path */public static String Getexternalstoragepath () {if (isexterNalstoragewritable ()) return Environment.getexternalstoragedirectory (). GetAbsolutePath (); Elsereturn null;} /** * Get Download directory path * * @return external memory card download path */public static String Getexternaldownloadpath () {return environment.getexternalstor Agepublicdirectory (environment.directory_downloads). GetAbsolutePath ();} /** * Write file to root path * * @param filename filename * @param content context * @return Write success */public Static Boolean write (String filename , String content) {return write ("/", fileName, content);} /** * to the root directory * * @param filename * @param bytes file byte array * @return write successfully */public static Boolean writebytes (String fi Lename, byte[] bytes) {return writebytes ("/", FileName, bytes);} /** * Writes a string to a file in the specified directory, the path begins/ends with a * * @param path relative to the root path, the path starts with/begins with A/end * @param filename filename * @param content file Contents * @retur n whether the write succeeds */public static Boolean write (string path, string filename, string content) {return writebytes (path, filename, CO Ntent.getbytes ());} /** * Writes a byte array to a file of the specified directory, the path begins/ends with a * * @param path relative to the root path, the path starts with/begins with/ends * @pAram filename * @param bytes byte array * @return */public static Boolean writebytes (string path, string fileName, byte byte  S[]) {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 (Filenotfoun Dexception e) {e.printstacktrace ()} catch (IOException e) {e.printstacktrace ();} finally {if (FOS! = null) {try {Fos.clos E ();} catch (IOException e) {e.printstacktrace ();}}} return flag;} /** * Read bytes from root path * * @param filename * @return byte array */public static byte[] readbytes (String filename) {return readbytes ( "/", FileName);} /** * Read bytes from the specified directory, path with/start/end * * @param path relative to the root path, path begins with/start with/end * @param filename * @return byte array */public static byte[ ] Readbytes (string path, string fileName) {File File = new file (Getexternalstoragepath () + path + fileName), if (!file.isfile ()) {return null;} else {FileInputStream FIS = null;try {fis = new FileInputStream (file); int length = Fis.available (); byte[] buffer = new Byte[length];fis.read (buf fer); return buffer;} catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} finally {if (FIS! = Nu ll) {try {fis.close ();} catch (IOException e) {e.printstacktrace ()}}} return null;}} /** * Read text from root * * @param filename filename * @return string */public static string read (string fileName) {return read ("/", Filena Me);}  /** * Read text from specified directory, path with/start/end * * @param path relative to root path, path begins with/start with/end * @param filename filename * @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;} /** * Remove from root * * @param filename filename * @rEturn whether to delete the successful */public static Boolean delete (String filename) {return Delete ("/", FileName);} /** * Removed from the specified directory, path with/start/end * * @param path relative to the root path, path with/start with/end * @param filename * @return Whether to delete succeeded */public static bool EAN Delete (string path, string fileName) {File File = new file (Getexternalstoragepath () + path + fileName); if (file.exists ()) return File.delete (); Elsereturn true;}}

Built-in memory 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 Storage Card Tool class * * @author Lizhangqu * @version 1.0 */public class Internalstorageutil {/** * in the original Append content * * @param context context * @param filename * @param content Append text * @return Append success */public Static Boolean Appen D (Context context, String filename,string content) {return writebytes (context, FileName, Content.getbytes (), true);} /** * Write file, file exists overwrite * * @param context context * @param filename * @param content Write text * @return Write success */public static B Oolean Write (context context, string filename, string content) {return writebytes (context, FileName, content.getbytes (), FALSE);} /** * Write Bytes * * @param context context * @param filename * @param content Write bytes * @return Write successfully */public static Boolean W Ritebytes (context context, String fileName,Byte[] content) {return writebytes (context, fileName, content, false);} /** * Write to the file, when the file exists according to the parameters isappend determine whether to overwrite * * @param context context * @param filename * @param content Write bytes * @param isappend Whether to append * @return whether to write successfully */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.M Ode_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 (fou T! = null) {fout.close (); fout = null;}} catch (IOException e) {e.printstacktrace ();}} return flag;} /** * Read File * * @param context context * @param filename * filename * @return The contents of the file string */public Static-string read (context, S Tring 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 contexts * @param filename * @return byte array */public static byte[] Readbytes (context context, String fil ename) {FileInputStream fin = null;byte[] buffer = null;try {fin = context.openfileinput (fileName); int length = Fin.availa BLE (); buffer = new Byte[length];fin.read (buffer);}  catch (FileNotFoundException e) {e.printstacktrace (),} catch (IOException e) {e.printstacktrace ();} finally {try {if (fin ! = null) {fin.close (); fin = null;}} catch (IOException e) {e.printstacktrace ();}} return buffer;} /** * Clears all files when a file is not cleared and returns false * * @param context Context * @return whether clear success */public static Boolean clear (context context) {Bo Olean flag = true; string[] files = context.filelist (); for (String filename:files) {Boolean result = Context.deletefile (fileName); if (Resul T = = false) {flag = false;}} return flag;} /** * Purge files based on file name * * @param context context * @param filename filename * @return Whether to delete success */publicStatic Boolean Delete (context context, String filename) {return context.deletefile (fileName);} /** * Returns the absolute path of internal storage * * @param context Context * @return App built-in folder path */public static String Getfiledir (context context) {File fi Lesdir = Context.getfilesdir (); return Filesdir.getabsolutepath ();}}
Reading of resource files

Package Cn.edu.zafu.utils;import Java.io.ioexception;import Java.io.inputstream;import Java.io.unsupportedencodingexception;import android.content.context;/** * Assert Resource Read * * @author Lizhangqu * @version 1  .0 */public class Resoucefileutil {/** * reads a text resource from the Assert folder * * @param context context * @param filename * filename * @return file content string */public static string Readstringfromassert (context context, string fileName) {string result = null;byte[] buffer = readb Ytesfromassert (context, fileName), try {result = new String (buffer, "UTF-8"),} catch (Unsupportedencodingexception e) { E.printstacktrace ();} return result;} /** * Read the text resource from the Raw folder * * @param context context * @param RAWID raw Resource ID * @return file content string */public static string Readstringfro Mraw (context context, int rawid) {String result = null;byte[] Buffer = Readbytesfromraw (context, rawid); try {result = new String (buffer, "UTF-8");} catch (Unsupportedencodingexception e) {e.printstacktrace ();} return result;} /** * Read files from the Assert folder to a byte array * * @param contextbelow * @param filename * @return file byte array */public static byte[] Readbytesfromassert (context context, String filename) {in Putstream is = null;byte[] Buffer = null;try {is = Context.getassets (). open (fileName); int size = is.available (); buffer = n EW 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 file from raw folder to byte array * * @param context context * @param RAWID raw Resource ID * @return file byte array */public static byte[] Readbytesfr Omraw (context context, int rawid) {InputStream is = null;byte[] Buffer = null;try {is = Context.getresources (). Openrawreso Urce (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;}}


Operation of the Sharedpreference

Package Cn.edu.zafu.utils;import Android.content.context;import android.content.sharedpreferences;/** * Sharedpreference Mode persisted Data Tool class * * @author Lizhangqu * @version 1.0 */public class Sharedpreferenceutil {/** * Save key value pair * * @p Aram Context * @param filename * @param key * @param value value * @return Save succeeded */public Static Boolean set (Contex T 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 ();} /** * Gets the value corresponding to the key, if not, returns "" * @param context Context * @param filename * @param key * @return value, no then return "" */public static S Tring Get (context context, string filename, string key) {return get (context, fileName, Key, "");} /** * Gets the value corresponding to the key, if not, returns DefaultValue * * @param context context * @param filename * @param key * @param defaultvalue default value * @return value, no return defaultvalue */public staticString get (context context, string fileName, String key,string defaultvalue) {sharedpreferences sharedpreferences = Conte Xt.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 * @param key * @return Remove successful */public static Boolean remove (Conte XT 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 the contents of the file * @param context context * @param filename * @return Whether to clear the successful */public static Boolean clear (context, St Ring fileName) {sharedpreferences sharedpreferences = context.getsharedpreferences (filename, context.mode_private); Sharedpreferences.editor Editor = Sharedpreferences.edit (); Editor.clear (); return Editor.commit ();} /** * Whether an item exists * @param context context* @param filename * @param key * @return The value of the key exists */public static Boolean Contatins (context context, String Filena Me,string key) {sharedpreferences sharedpreferences = context.getsharedpreferences (FileName, context.mode_private); return Sharedpreferences.contains (key);}}


Overview of the Android Data Persistence tool class

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.