How to store the data of Android development _android

Source: Internet
Author: User
Tags getdate readable file permissions stringbuffer

In Android, the storage of data is divided into two ways:

1, directly in the form of files stored in the directory

2, in the JSON format stored in the database

There are two different ways to store data in a file:

1. txt file generation

2. Generate XML file

So let's go into the details today and save it as a file, and as a result of not talking about the database, the JSON format is stored in the database in the course that follows.

First, generate a. txt file

The generation of files is nothing more than a part of the input and output stream we learn in Java, and the Java Foundation is believed to be easy to understand, because it's really easy.

1, the production directory can be divided into two types:

1) This machine

2) SD Card

2, the way to generate a. txt file can be divided into 4 kinds

1 use mode_private mode to generate a private file

2 use Mode_private mode to generate a appent file

3 use mode_world_readable mode to generate a readable file

4 use mode_world_writeable mode to generate a writeable file

Before the. txt file, it is necessary to understand the permissions of the file, as shown in the following figure:

1, the first lattice: the type of file

2, 第2-4: means the current user has permissions

3, 第5-7: Represents the rights of the current user's group

4, 第8-10: means other users have the rights

5, "R": to Be readable; "W": To be writable; "X": to indicate executable; "-": What permissions are not, if you see "rwx" means readable writable executable, other combinations are also so

Note: The permissions for files generated by different schemas are not the same, and the permissions for the type of file generated are not the same.

So here are a few ways to say it in detail

1, as shown in the picture, when we click button to trigger the file monitor, the button here is a simple button, but to remember to set the onclick click event Properties Oh ~ Everyone is not stupid is it ...

1 use mode_private mode to generate a private file

Click button 1, using Mode_private mode, to generate a private file public
  void Click1 (View v) {
    try {
      FileOutputStream fos = Openfileoutput ("Private.txt", mode_private);
      Fos.write ("Private". GetBytes ());
      Fos.close ();
    } catch (Exception e) {
      e.printstacktrace ();
    }
  }

2 use Mode_private mode to generate a appent file

Click button 2, using Mode_private mode, to generate a appent file public
  void Click2 (View v) {
    try {
      FileOutputStream fos = Openfileoutput ("Appent.txt", mode_private);
      Fos.write ("Appent". GetBytes ());
      Fos.close ();
    } catch (Exception e) {
      e.printstacktrace ();
    }
  }

3 use mode_world_readable mode to generate a readable file

Click button 3, using mode_world_readable mode, to generate a readable file public
  void Click3 (View v) {
    try {
      FileOutputStream FOS = Openfileoutput ("Readable.txt", mode_world_readable);
      Fos.write ("readable". GetBytes ());
      Fos.close ();
    } catch (Exception e) {
      e.printstacktrace ();
    }
  }

4 use mode_world_writeable mode to generate a writeable file

 Click button 4, using mode_world_writeable mode, to generate a write file public
  void Click4 (View v) {
    try {
      FileOutputStream fos = Openfileoutput ("Writeable.txt", mode_world_writeable);
      Fos.write ("writeable". GetBytes ());
      Fos.close ();
    } catch (Exception e) {
      e.printstacktrace ();
    }
  }

Part of the Code description

FileOutputStream: File output stream

Openfileoutput ("Private.txt", mode_private): Openfileoutput is the encapsulated file output stream in Android, Private.txt is the generated file name, Mode_ Private this is the model mentioned above!

Fos.write ("Private"). GetBytes ()): Write is what to write, the argument here is the text you want to write, GetBytes () ... ^_^ don't know how to see the basics of java. hahaha ~ ~ ~

Close (): Closes Stream object

Try-catch: There are exceptions, try it ...

Mode_world_writeable,mode_world_readable: These two modes have been discarded ... Not so much why! Ha ha ...

Feel oneself Meng Meng ... It's really not going to review the basics of Java!

So here's the 4 files that are generated as shown in the following figure

2, the file stored in the SD card

1, get the path of SD card:

String Sdpath = Environment.getexternalstoragedirectory (). GetPath ();

2, add the path

File File = new file (Sdpath + "Writeable.txt");

And then the path to write this is good! It's so simple.

3, read the file just written

What is the path you write when reading the contents of a file, then what is the path to read?

try {
      //file file = new file ("/data/data/com.test.filereadwrite/files/readable.txt");
      File File = new file ("/data/data/com.test.filereadwrite/files/writeable.txt");
      FileInputStream fis = new FileInputStream (file);
      BufferedReader BFFR = new BufferedReader (new InputStreamReader (FIS));
      String content = Bffr.readline ();
      Toast.maketext (mainactivity.this, Content,). Show ();
    catch (Exception e) {
      e.printstacktrace ();
    }

4. Path optimization

I have found that I am here directly to write the path, so this writing is not the most optimized, then how to be more optimized, so long as long as only two lines of code is good, for example:

1, get the path:

String path = Context.getfilesdir (). GetPath ();

2, add the path:

File File = new file (path + "Writeable.txt");

Note: We write the path should be optimized in this way, and should not be written dead, here I for Shajijinghou ha ha ~ so I wrote dead ... But the effect is the same Wow ~ ~

Ii. Generating XML files

There are two different ways to generate XML files:

1. Using native StringBuffer to splice XML files

2, the use of Android packaging good Xmlpullparser class

The XML files generated in both ways are the same, but individuals prefer the second way, because simplicity is simple, simple enough that Google engineers don't have to write instance code in their development documents ...

Before you generate XML, you should not forget to write an entity class, otherwise how do you encapsulate the data? Tell me how to package .....

So here we go directly to the code (entity classes write for themselves ...). )

@Override
  protected void onCreate (Bundle savedinstancestate) {
    super.oncreate (savedinstancestate);
    Setcontentview (r.layout.activity_main);
    
    Initialize the data we want to back up
    smslists = new arraylist<sms> ();
    
    Insert test data for
    (int i = 0; i < i++) {
      SMS SMS = new SMS ();
      Sms.setaddress ("10086" +i);
      Sms.setbody ("Hello" +i);
      Sms.setdate ("201" +i);
      Add SMS objects to the collection
      Smslists.add (SMS);
    }
  

1. Using native StringBuffer to splice XML files

Click the button button1 to generate an XML file public void Click1 (View v) {//1 Create a StringBuffer object stringbuffer sb = NE in stringbuffer way
    
    W StringBuffer ();
    Start the group spelling XML file Header sb.append ("<?xml version=\" 1.0\ "encoding=\" utf-8\ "?>");
    Start the group spelling XML root node sb.append ("<smss>");
      
      Start the group spelling Sms node and child node for (SMS sms:smslists) {sb.append ("<sms>");
      Group Addressa node Sb.append ("<address>");
      Sb.append (Sms.getaddress ());
      
      Sb.append ("</address>");
      Group spelling Body node sb.append ("<body>");
      Sb.append (Sms.getbody ());
      
      Sb.append ("</body>");
      Group spell date node Sb.append ("<date>");
      Sb.append (Sms.getdate ());
      
      Sb.append ("</date>");
    Sb.append ("</sms>");
    
    //SMSS node End sb.append ("</smss>");
      Save the data to the SD card try {File File = new file (Environment.getexternalstoragedirectory (). GetPath (), "Smsbackup.xml"); FileOutputStream FOS = nEW FileOutputStream (file);
      Fos.write (Sb.tostring (). GetBytes ());
    Fos.close ();
    catch (Exception e) {e.printstacktrace ();
 } 
    
  }

2, using the Android encapsulated Xmlpullparser class

Click on the button button2 to generate the XML file public void Click2 (View v) {try {///Get the instance of the XmlSerializer class through XML this tool class in XmlSerializer way to get
      XmlSerializer serializer = Xml.newserializer ();
      Sets the xmlserializer serialization parameter file File = new file (Environment.getexternalstoragedirectory (). GetPath (), "Smsbackup.xml");
      FileOutputStream fos = new FileOutputStream (file);
      Serializer.setoutput (FOS, "utf-8");
      Starts writing the XML document at the beginning serializer.startdocument ("Utf-8", true);
      The root node of the Write XML namespace namespace Serializer.starttag (null, "SMSS");
        
        Traverse the SMS node and child node for (SMS sms:smslists) {Serializer.starttag (null, SMS);
        Group Addressa node Serializer.starttag (null, "address");
        Serializer.text (Sms.getaddress ());
        
        Serializer.endtag (NULL, "address");
        Group spelling Body node Serializer.starttag (null, "body");
        Serializer.text (Sms.getbody ());
        
        Serializer.endtag (NULL, "body"); Group spell Date Node serializeR.starttag (NULL, "date");
        Serializer.text (Sms.getdate ());
        
        Serializer.endtag (NULL, "date");
      Serializer.endtag (NULL, "SMS");
      
      } Serializer.endtag (null, "SMSS");
      End of XML serializer.enddocument ();
      
    Close flow fos.close ();
    catch (Exception e) {e.printstacktrace ();
 }
  }

So here's the XML file that generates the following diagram:

3. Read the data in the XML file

@Override
  protected void onCreate (Bundle savedinstancestate) {
    super.oncreate (savedinstancestate);
    Setcontentview (r.layout.activity_main);
    
    try {
      //Display data information
      TextView tv_sms = (TextView) Findviewbyid (r.id.tv_weather);
      Manager InputStream in = Getassets () with the context to obtain an asset
      . Open ("Smss.xml");
      Call us to define the business method of parsing xml
      list<sms> smslists = Smsparser.xmlparser (in);
      
      StringBuffer sb = new StringBuffer ();
      for (Sms sms:smslists) {
        sb.append (sms.tostring ());
      }
      
      Display the data to the TextView
      Tv_sms.settext (sb.tostring ());
      
    } catch (Exception e) {
      e.printstacktrace ();
    }
  }

Partial Code Description:

Here I want to teach you how to see the development document ... So let's go see the development document for ourselves ... Ha ha ~ ~

PS: Here I would like to explain, not I will not, nor lazy, but everyone in the future when the enterprise development can be viewed in the development of documents, and to tell the truth about Android is really a lot of things, to all remember that is simply too difficult ...

So I hope everyone can learn to view the development document ... This is also a compulsory course for me ~ ~ Because for small white I, learned to look at the document to avoid a lot of trouble, such as suddenly have a dongdong not ... What to do? Ha ha ...

Third, summary    

1, to generate a. txt file 4 ways and steps

2.2 ways and steps to generate XML files

3. Reading. txt files

4. Read XML file

5, the data stored in the local and SD card

6, learn to see the development of documents

7, file permissions

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.