Android Learning File Store Read _android

Source: Internet
Author: User
Tags gettext mkdir readline sqlite database stringbuffer

Objective

I believe we all know that in Androidos, v data storage is provided in the following ways:contentprovider storage, file storage, sharedpreference storage, SQLite database storage, networked storage . So this article, we introduce file storage.

1.Android file Mode of operation

Students who have studied Java know that we create new files, and then we can write data, but Android is different because Android is based on Linux, and when we read and write files, we also need to add the operating mode of the file, the operating mode of Android is as follows:

2, the operation mode of the file

When we are learning Java, we all know that the IO operation in Java to save and read files, Android is based on Linux, and Java is the different Android in the context of the package of input and output flow of the acquisition method, respectively: FileInputStream openfileinput (String name); FileOutputStream (String name, int mode), where the first parameter specifies the file name, and the second specifies the mode in which to open the file. The file modes provided by Android are:

1.mode_private:android provides the default mode of operation, which means that the file is private and can only be accessed by the application itself, in which case the written content overwrites the contents of the original file.

2.mode_append: Mode checks whether the file exists, appends to the file, or creates a new file.

3.mode_world_readable: Indicates that the current file can be read by other applications;

4.mode_world_writeable: Indicates that the current file can be written by another application.

In addition, Android offers several other important ways to file operations:

1.getDir (String name, int mode): Gets or creates a subdirectory of name in the application's Data folder

2.File Getfilesdir (): Get the absolute path under the app's Data directory

3.string[] FileList (): Returns all files in the app's data directory

4.deleteFile (String fileName): Delete the specified file in the app's data directory

3. Read and Write files

Android's read and write files are the same as Java, which is done through IO operations, and here's a simple example of this process:

Layout file Code:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/"
Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:orientation=" vertical " android:padding= "16DP" > <edittext android:id= "@+id/ed_file_save" android:layout_width= "Match_parent" Android
  : layout_height= "wrap_content"/> <button android:id= "@+id/btn_file_save" android:layout_width= "Match_parent" android:layout_height= "Wrap_content" android:layout_margintop= "10DP" android:text= "Save Content"/> <Button android: Id= "@+id/btn_file_read" android:layout_width= "match_parent" android:layout_height= "Wrap_content" Android:layout_ margintop= "10DP" android:text= read content "/> <textview android:id=" @+id/tv_read_file "android:layout_width=" Match_ Parent "android:layout_height=" wrap_content "android:layout_margintop=" 10DP "android:textcolor=" #000 "Android:text Size= "14sp"/> </LinearLayout>

Activity code:

Package com.example.datasave;
Import Android.content.Context;
Import Android.os.Bundle;
Import android.support.annotation.Nullable;
Import android.support.v7.app.AppCompatActivity;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.EditText;

Import Android.widget.TextView;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;

Import java.io.IOException;
 /** * Created by Devin on 2016/7/19.
* * public class Filedataactivity extends Appcompatactivity {private EditText ed_file_save, private Button btn_file_save;
Private Button Btn_file_read;
Private TextView Tv_read_file;

Private String FileName = "Hello.txt";
  @Override protected void OnCreate (@Nullable Bundle savedinstancestate) {super.oncreate (savedinstancestate);
  Setcontentview (R.layout.activity_file);
  Ed_file_save = (edittext) Findviewbyid (R.id.ed_file_save);
  Btn_file_save = (Button) Findviewbyid (R.id.btn_file_save);
  Btn_file_read = (Button) Findviewbyid (R.id.btn_file_read); TV_read_file = (TextView) Findviewbyid (r.id.tv_read_file); Btn_file_save.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (view view) {STR
      ing filecontent = Ed_file_save.gettext (). toString ();
        try {Save (filecontent);
      Toastutils.showtoast (filedataactivity.this, "File write success");
        catch (Exception e) {e.printstacktrace ();
      Toastutils.showtoast (filedataactivity.this, "file write Failed");
  }
    }
  });  Btn_file_read.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (view view) {Try
        {String content = read ();
      Tv_read_file.settext ("The contents of the document is:" + content);
        catch (IOException e) {e.printstacktrace ();
      Toastutils.showtoast (filedataactivity.this, "Read file failed!");
}
    }
  }); public void Save (String filecontent) throws Exception {FileOutputStream output = This.openfileoutput (FileName, conte Xt.
  Mode_private); Output.write (FileconteNt.getbytes ());
Output.close ();
  Public String Read () throws IOException {//Open file input stream FileInputStream input = This.openfileinput (fileName);
  byte[] temp = new byte[1024];
  StringBuffer StringBuffer = new StringBuffer ("");
  int len = 0;
  while (len = input.read (temp)) > 0) {stringbuffer.append (new String (temp, 0, Len));
  //Close the input stream input.close ();
return stringbuffer.tostring (); }
}

Finally, the implementation of the effect diagram:

The pattern used here is private mode , which can only be read by this application and overwrite the original file, so that simple file reading and writing will be realized.

4. Read and write SDcard documents

Read and write SDcard requires permissions:

<uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission Android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>

On the device to read and write SDcard need to determine whether the existence of sdcard, many mobile phones do not exist sdcard, the following we have to SDcard reading and writing will be reflected, the following we together through the example to achieve sdcard read and write operations

First, the layout file code:

<edittext
  android:id= "@+id/ed_file_save_sd"
  android:layout_width= "match_parent"
  android:layout_ height= "Wrap_content"
  android:layout_margintop= "20DP"/>

<button android:id=
  "@+id/btn_file_" SAVE_SD "
  android:layout_width=" match_parent "
  android:layout_height=" wrap_content "
  android:layout_" margintop= "10DP"
  android:text= "write to SDcard"/>

<button android:id=
  "@+id/btn_file_read_sd"
  android:layout_width= "match_parent"
  android:layout_height= "wrap_content"
  android:layout_ margintop= "10DP"
  android:text= "read from SDcard"/>

<textview android:id=
  "@+id/tv_read_file_sd"
  android:layout_width= "match_parent"
  android:layout_height= "wrap_content"
  android:layout_ margintop= "10DP"
  android:textcolor= "#000"
  android:textsize= "14sp"/>

Activity code:

  ED_FILE_SAVE_SD = (edittext) Findviewbyid (R.ID.ED_FILE_SAVE_SD);
  TV_READ_FILE_SD = (TextView) Findviewbyid (R.ID.TV_READ_FILE_SD);
  BTN_FILE_READ_SD = (Button) Findviewbyid (R.ID.BTN_FILE_READ_SD);
      Btn_file_read_sd.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (view view) {
        try {String content = READFROMSD ();
      Tv_read_file_sd.settext (read from SDcard: "+ content);
        catch (Exception e) {e.printstacktrace ();
      Toastutils.showtoast (filedataactivity.this, "Read file failed!");
  }
    }
  });
  BTN_FILE_SAVE_SD = (Button) Findviewbyid (R.ID.BTN_FILE_SAVE_SD);
      Btn_file_save_sd.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (view view) {
      String content = Ed_file_save_sd.gettext (). toString ();
        try {save2sdcard (content);
      Toastutils.showtoast (filedataactivity.this, "file write SDcard successful");
        catch (Exception e) {e.printstacktrace ();Toastutils.showtoast (filedataactivity.this, "File write SDcard failed");

}
    }
  }); public void Save2sdcard (String content) throws Exception {if (Environment.getexternalstoragestate (). Equals ( environment.media_mounted)) {//if sdcard exists a String FileName3 = Environment.getexternalstoragedirectory (). getcanonical
    Path () + file.separator + "Test" + File.separator + fileName2;
    File File = new file (FileName3);
    if (!file.getparentfile (). exists ()) {File.getparentfile (). mkdir ();
    } fileoutputstream FileOutputStream = new FileOutputStream (file);
    Fileoutputstream.write (Content.getbytes ());
  Fileoutputstream.close ();
  else {toastutils.showtoast (this, "SDcard does not exist");
  } public String Readfromsd () throws Exception {StringBuffer stringbuffer = new StringBuffer (""); if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {String FileName3 = Environment.getexternalstoragedirectory (). Getcanonicalpath () + file.separator + "Test" + FilE.separator + fileName2;
    File File = new file (FileName3);
    if (!file.getparentfile (). exists ()) {File.getparentfile (). mkdir ();
    } fileinputstream FileInputStream = new FileInputStream (file);
    byte[] temp = new byte[1024];
    int len = 0;
    while (len = fileinputstream.read (temp)) > 0) {stringbuffer.append (new String (temp, 0, Len));
  } fileinputstream.close ();
  else {toastutils.showtoast (this, "SDcard does not exist");
return stringbuffer.tostring (); }

SDcard Read and file operation is similar, need to judge whether SDcard exists, finally is the effect chart:

5, read raw and assets files of data

The files in the raw/res will be mapped to the Android R file, we can access it directly through the R file, not too much here.

The files in assets are not mapped to r files like files in Raw/res, can have directory structure, and Android provides a Assetmanager object to access assets files, and our visit is simple:

Assetmanager Assetsmanager = Getassets (); 
InputStream InputStream = Assetsmanager.open ("FileName");

This allows you to get directly to the resource files in the assets directory.

Androidos file storage is a simple introduction to this, here are some tools for file storage:

Package Com.example.datasave.io;

Import Android.content.Context;
Import Java.io.BufferedReader;
Import Java.io.BufferedWriter;
Import Java.io.ByteArrayOutputStream;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;

Import Java.io.OutputStreamWriter; /** * IO streaming tool class <br> * Very simple, only support text operation/public class Ioutils {/** * Text write operation * * @param filePath file path. Be sure to add the file name <br> * For example:. /a/a.txt * @param content writing * @param append append/public static void Write (string filePath, string content, Boole
  An append) {bufferedwriter BUFW = null;
    try {BUFW = new BufferedWriter (new OutputStreamWriter (New FileOutputStream (FilePath, append));

  Bufw.write (content);
  catch (Exception E1) {e1.printstacktrace ();
      finally {if (BUFW!= null) {try {bufw.close (); catch (IOException E) {e.printstacktrace (); */** * Text Read operation * * @param path file, be sure to add file name <br> * For example:.
  /a/a.txt * @return/public static String read (String path) {BufferedReader bufr = null;
    try {bufr = new BufferedReader (new InputStreamReader (New FileInputStream (path));
    StringBuffer sb = new StringBuffer ();
    String str = NULL;
    while (str = Bufr.readline ())!= null) {sb.append (str);
  return sb.tostring ();
  catch (Exception e) {e.printstacktrace ();
      finally {if (BUFR!= null) {try {bufr.close ();
      catch (IOException e) {e.printstacktrace ();
}} return null; /** * Text Read operation * * @param is input stream * @return/public static String read (InputStream is) {BufferedReader BUFR = n
  ull;
    try {bufr = new BufferedReader (new InputStreamReader (IS));
    StringBuffer sb = new StringBuffer ();
    String str = NULL; while (str = Bufr.readline ())!= nulL) {sb.append (str);
  return sb.tostring ();
  catch (Exception e) {e.printstacktrace ();
      finally {if (BUFR!= null) {try {bufr.close ();
      catch (IOException e) {e.printstacktrace ();
}} return null; /** * @param context * @param filename filename * @return byte array/public static byte[] Readbytes
  Tring 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.printstacktrace ();
        Finally {try {if (fin!= null) {fin.close ();
      Fin = null;
    } catch (IOException e) {e.printstacktrace ();
} return buffer; /** * Fast Reader Application package file content * * @param context * @param filename * @return File contents *@throws IOException */public static String read (context, String filename) throws IOException {FILEINPUTST
  Ream instream = context.openfileinput (filename);
  Bytearrayoutputstream OutStream = new Bytearrayoutputstream ();
  byte[] buffer = new byte[1024];
  int len = 0;
  while (len = instream.read (buffer))!=-1) {outstream.write (buffer, 0, Len);
  } byte[] data = Outstream.tobytearray ();
return new String (data); }


}

OK, about Android data storage and access to the file to read and write it here, if you are learning this article encountered any problems, or feel some flaws in the place, welcome to put forward, extremely grateful, thank you ~

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.