Android file operations
From the application Data directory can be seen, the data file can be divided into two categories, one is placed in the extended memory files, that is, the files in the/sdcard/directory, they can be shared by each application, and the other is placed in the Application Data directory files, they can only be used by individual applications, can not be read and written by other applications.
(1) The file read and write mode in the extended memory is the same as standard Java file processing.
We can create a new Fileutil tool class to help us handle the I/O operation of the file, first we first determine the status of the SD card, see if the SD card is available, how much usable capacity, etc. Create a new class of fileutil, add a method
1//=================get sdcard information=================== 2 public static Boolean issdcardavailable () {3 String status = Environment.getexternalstoragestate (); 4//environment.media_mounted indicates that the SD card is mounted properly 5 if (Status.equals (environment.media_mounted)) {6 ret Urn true; 7} 8 return false; 9}10 One public static long getsdallsizekb () {//SD card location of File path = Environment.getexternalsto Ragedirectory ();//statfs gets all the StatFs SF = new StatFs (Path.getpath ()) in blocks, and 16//Get a single bloc The size of k BlockSize = Sf.getblocksize (); 18//Gets all data blocks the number of long allblocks = Sf.getblockcount (); 20 Return SD card size return (Allblocks * blockSize)/1024; KB22}23/**25 * Free size for normal APPLICATION26 * @return27 */28 public static long G ETSDAVALIBLESIZEKB () {File path = environment.getexternalstoragedirectory (); 30 StatFs SF = new StatFs (Path.getpath ()), a long blockSize = Sf.getblocksize (), and a long avaliablesize = SF. Getavailableblocks (); return (Avaliablesize * blockSize)/1024;//KB34}
Environment.getexternalstoragedirectory () indicates the directory where the extended storage is obtained. (It is recommended to use this method dynamically, because sdcard This directory path is configurable)
Statfs.getblocksize after API18 to Statfs.getblocksizelong, other similar getblock methods, about StatFs, details can read this blog
Then join the event in the activity button1
Case R.id.button1: { log.d ("TEST", "SDcard?") +fileutil.issdcardavailable ()); LOG.D ("TEST", "Full capacity" + (float) fileutil.getsdallsizekb ()/1024/1024); LOG.D ("TEST", "Usable capacity" + (float) fileutil.getsdavaliblesizekb ()/1024/1024); Toast.maketext (This, "status", Toast.length_short). Show (); break; }
The operation results are as follows
Next we will determine if a folder exists in the SD card and create a folder
/** * @param director folder name * @return * /public static Boolean Isfileexist (String director) { File File = new file (environment.getexternalstoragedirectory () + file.separator + director); return file.exists (); } /** * Create multiple director * @param path * @return * /public static Boolean CreateFile ( String director) { if (Isfileexist (director)) { return true; } else { file file = new file (environmen T.getexternalstoragedirectory () + file.separator + director); if (!file.mkdirs ()) { return false; } return true; } }
Where File.separator is the delimiter, different operating systems, such as Windows is representative of the "/", but under Linux represents "\". So mind using file.separator instead of delimiters. File.mkdirs () indicates that a folder is created and can be accompanied by the creation of a parent directory, while MkDir () does not, the file for details can be viewed in the official documentation, or read this blog post
Then add a response event to the button2 in the activity
Case R.id.button2: { log.d ("TEST", "Example folder exists?") +fileutil.isfileexist ("example")); LOG.D ("TEST", "Create Forexample folder" +fileutil.createfile ("Forexample")); Toast.maketext (This, "Isfile", Toast.length_short). Show (); break; }
After running, you can see
We will find a new Forexample folder in the SDcard directory of the phone.
Finally, we will implement the reading and writing of the file.
Write:
/** * * @param director * (you don ' t need to begin with * ENVIRONMENT.GETEXTERNALST Oragedirectory () +file.separator) * @param fileName * @param content * @param encoding * (UTF-8. ..) * @param isappend *: Context.mode_append * @return * */public static File Writetosdcardfile (stri ng directory, string fileName, string content, String encoding, Boolean isappend) {//mobile SD card PA Th +path file file = null; OutputStream OS = null; try {if (!createfile (directory)) {return file; } file = new file (environment.getexternalstoragedirectory () + file.separator + directory + F Ile.separator + fileName); OS = new FileOutputStream (file, isappend); if (Encoding.equals ("")) {Os.write (Content.getbytes ()); } else {Os.write (content.getbytes(encoding)); } os.flush (); } catch (IOException e) {log.e ("Fileutil", "Writetosdcardfile:" + e.getmessage ()); } finally {try {if (OS! = null) {os.close (); }} catch (IOException e) {e.printstacktrace (); }} return file; }/** * Write data from InputStream to SDcard */public File writetosdcardfrominput (string directory, string FileName, InputStream Input) {file file = null; OutputStream OS = null; try {if (createFile (directory)) {return file; } file = new file (environment.getexternalstoragedirectory () + file.separator + directory + F Ile.separator + fileName); OS = new FileOutputStream (file); byte[] data = new Byte[bufferd]; int length =-1; while (length = Input.reAD (data))! =-1) {os.write (data, 0, length); }//Clear cache Os.flush (); } catch (Exception e) {log.e ("Fileutil", "" "+ E.getmessage ()); E.printstacktrace (); } finally {try {os.close (); } catch (Exception e) {e.printstacktrace (); }} return file; }
As you can see from the above, there are two ways to write, one to write the string directly, and one to write the data stream to a file. Another thing to mention is that the default directory for file is SDcard directory, so you don't have to add SDcard directory paths every time.
FileOutputStream (file, isappend) two parameters, the left side is a file, and the right is a Boolean value, True, the data will be followed by the original file written, and false is overwritten.
Read:
public static string Readfromsdcardfile (String directory,string fileName) { string res= ""; File file = null; File = new file (environment.getexternalstoragedirectory () + file.separator + directory + file.separator + fileName); try { FileInputStream fis = new FileInputStream (file); int length = fis.available (); byte [] buffer = new Byte[length]; Fis.read (buffer);
Converts bytes into string res = encodingutils.getstring (buffer, "UTF-8") in encoded format; Fis.close (); return res; } catch (FileNotFoundException e) { //TODO auto-generated catch block log.d ("TEST", "FileNotFound"); E.printstacktrace (); } catch (Exception e) { log.d ("TEST", "Can not Open File"); E.printstacktrace (); } return null; }
The encoding is UTF-8 by default, and if you want to change it, pass it as a parameter.
Add a response to the button in the activity
Case R.id.button3: { fileutil.writetosdcardfile ("Forexample", "test.txt", edittext.gettext (). toString (), " UTF-8 ", true); Toast.maketext (This, "WriteFile", Toast.length_short). Show (); break; } Case R.ID.BUTTON4: { textview.settext (fileutil.readfromsdcardfile ("Forexample", "test.txt")); Toast.maketext (This, "ReadFile", Toast.length_short). Show (); break; }
Write "I am CPACM" on the text edit box, click the WriteFile button First, then click ReadFile to get the result of running.
At the same time in the root directory of the Forexample folder will find Test.txt, which has "I am CPACM" line of words. To this, the file reads and writes successfully.
(2) file reading and writing in the Application Data directory
The private data directory stored in the application directory is usually not read and written directly through the file class, but is manipulated using some encapsulated classes or functions. It is generally possible to execute through Context.openfileoutput.
Add two methods to the activity, reading and writing the files, respectively
public void WriteFile (String filename,string writestr) { try{ fileoutputstream fout =openfileoutput (FileName, Mode_private); byte [] bytes = Writestr.getbytes (); Fout.write (bytes); Fout.close (); } catch (Exception e) { e.printstacktrace (); } } Read Data public string ReadFile (String fileName) { string res= ""; try{ fileinputstream fin = openfileinput (fileName); int length = fin.available (); byte [] buffer = new Byte[length]; Fin.read (buffer); res = encodingutils.getstring (buffer, "UTF-8"); Fin.close (); } catch (Exception e) { e.printstacktrace (); } return res; }
Also add in the response of the button
Case R.ID.BUTTON5: { WriteFile ("Test2.txt", Edittext.gettext (). toString ()); Toast.maketext (This, "Writeprivatefile", Toast.length_short). Show (); break; } Case R.ID.BUTTON6: { textview.settext (readFile ("test2.txt")); Toast.maketext (This, "Readprivatefile", Toast.length_short). Show (); break; }
Follow the same picture.
Finally, don't forget to declare permissions in the configuration file
<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android: Name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>