In Android, data storage is divided into two ways:
1. Store directly in the directory as a file
2. Store in the database in json format
There are two ways to store data in files:
1. Generate a .txt file
2. Generate xml file
So today, let’s talk about storing in the form of files in detail. Since the database is not mentioned, we will talk about storing it in the database in json format in later courses.
1. Generate a .txt file
The generation of files is nothing more than a part of the input and output streams we learn in Java. I believe it is easy to understand with a Java foundation, because it is really simple~~
1. The generated directory can be divided into two types:
1) Native
2) SD card
2. There are four ways to generate .txt files
1) Use the MODE_PRIVATE mode to generate a private file
2) Use the MODE_PRIVATE mode to generate an 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 generating a .txt file, we need to understand the permissions of the file, as shown below:
1. The first cell: indicates the type of the file
2. Box 2-4: Indicates the permissions of the current user
3. Box 5-7: Indicates the permissions of the group the current user belongs to
4. Boxes 8-10: Indicate the permissions owned by other users
5. "r": means readable; "w": means writable; "x": means executable; "-": means no permission, if you see "rwx", it means readable, writable, and executable , and other combinations
Note: The permissions of the files generated by different modes are different, and the permissions of the types of generated files are also different.
Then, these methods will be described in detail below.
1. As shown in the figure, when we click the button button, the monitoring of the file is triggered. The button here is a simple button, but remember to set the attribute of the onclick click event~ Everyone is not stupid, right...
1) Use the MODE_PRIVATE mode to generate a private file
//Click button 1, use MODE_PRIVATE mode, 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 the MODE_PRIVATE mode to generate an appent file
//Click button 2, use MODE_PRIVATE mode, generate an 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, use MODE_WORLD_READABLE mode, 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, use MODE_WORLD_WRITEABLE mode, 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 packaged file output stream in Android, private.txt is the generated file name, and MODE_PRIVATE is the mode mentioned above!
fos.write("private".getBytes()): write is what to write, the parameter here is the text content you want to write, getBytes()…………… ^_^ I don’t know how to read Java by myself Basics hahaha~~~
close(): close the stream object
try-catch: There is an exception, try it...
MODE_WORLD_WRITEABLE, MODE_WORLD_READABLE: These two modes have been deprecated...not so much why! Hahaha……
I feel cute... If you really don't know how to do it, let's review the basics of Java!
Then here are 4 files as shown in the figure below
2. Store the file in the SD card
1. Get the path of the SD card:
String sdPath = Environment.getExternalStorageDirectory().getPath() ;
2. Add path
File file = new File(sdPath + "writeable.txt");
Then just write the path as this! it's that simple
3. Read the file just written.
When reading the content of the file, what is the path you write, then what is the path when reading?
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, 2000).show(); } catch (Exception e) { e.printStackTrace(); }
4. Path optimization
Everyone has discovered that I am directly writing the path here, so this way of writing is not optimal, so how can it be more optimized? Just change two lines of code for a long time, for example: 1
. Get path:
String path = Context.getFilesDir().getPath();
2. Add the path:
File file = new File(path + "writeable.txt");
Note: The paths we write should be optimized in this way, and should not be written to death. Here I am trying to scare the monkeys hahaha~ So I wrote it to death...but the effect is the same~~
Second, generate the xml file
The generation of xml files can be divided into two ways:
1. Using native StringBuffer to stitch xml files
2. Using Android packaged XmlPullParser class
to generate xml files are the same, but I personally prefer the second method because it is simple , It’s simple, so simple that Google engineers don’t need to write example codes in the development documents...
Before generating xml, don’t forget to write an entity class, otherwise how do you encapsulate data? Tell me how to encapsulate...
Then we will directly add the code here (write the entity class yourself...)
@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 < 10; i++) { Sms sms = new Sms(); sms.setAddress("10086"+i); sms.setBody("Hello"+i); sms.setDate("201"+i); //Add the sms object to the collection smsLists.add(sms); } }
1. Use native StringBuffer to stitch xml files
//Click the button button1 to generate an xml file through StringBuffer public void click1(View v){ //1 Create a StringBuffer object StringBuffer sb = new StringBuffer(); //Start to assemble the xml file header sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); //Start to assemble the xml root node sb.append("<smss>"); //Start to assemble sms nodes and child nodes for (Sms sms : smsLists) { sb.append("<sms>"); //Group addressa node sb.append("<address>"); sb.append(sms.getAddress()); sb.append("</address>"); //Assembly body node sb.append("<body>"); sb.append(sms.getBody()); sb.append("</body>"); //Assembly date node sb.append("<date>"); sb.append(sms.getDate()); sb.append("</date>"); sb.append("</sms>"); } //smss node end sb.append("</smss>"); //Save data to 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. Use Android packaged XmlPullParser class
//Click button button2 to generate xml file through XmlSerializer public void click2(View v){ try { // Get an instance of the XmlSerializer class through the tool class xml to get it XmlSerializer serializer = Xml.newSerializer(); //Set XmlSerializer serialization parameters File file = new File(Environment.getExternalStorageDirectory().getPath(),"smsbackup.xml"); FileOutputStream fos = new FileOutputStream(file); serializer.setOutput(fos,"utf-8"); //Start writing the beginning of the xml document serializer.startDocument("utf-8", true); //Write the root node namespace namespace of xml serializer.startTag(null, "smss"); //Traverse the sms node and its child nodes for (Sms sms : smsLists) { serializer.startTag(null, "sms"); //Group addressa node serializer.startTag(null, "address"); serializer.text(sms.getAddress()); serializer.endTag(null, "address"); //Assembly body node serializer.startTag(null, "body"); serializer.text(sms.getBody()); serializer.endTag(null, "body"); //Assembly date node serializer.startTag(null, "date"); serializer.text(sms.getDate()); serializer.endTag(null, "date"); serializer.endTag(null, "sms"); } serializer.endTag(null, "smss"); // end xml end serializer.endDocument(); // close the stream fos.close(); } catch (Exception e) { e.printStackTrace(); } }
Then the xml file as shown below is generated here: 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); // Get the manager of the asset through the context InputStream in = getAssets().open("smss.xml"); //Call the business method we define to parse xml List<Sms> smsLists = SmsParser.xmlParser(in); StringBuffer sb = new StringBuffer(); for (Sms sms : smsLists) { sb.append(sms.toString()); } //Display the data on the TextView tv_sms.setText(sb.toString()); } catch (Exception e) { e.printStackTrace(); } }
Part of the code description:
Here I want to teach you how to read the development documents by yourself... So let's go to the development documents by yourself... Hahaha~~
ps: Here I want to explain that it's not that I don't know how to be lazy, but Everyone will be able to view the development documents when the enterprise is developing in the future, and to be honest, there are really many things in Android, it is simply too difficult to remember all of them...so I hope
everyone can learn to view the development documents by themselves... This can be regarded as a compulsory course for me~~Because for me who is a novice, learning to read documents will save me a lot of trouble, such as suddenly there is something that I can't... What should I do? Hahaha...
3. Summary
1. 4 methods and steps to generate .txt files
2. 2 methods and steps to generate xml files
3. Read .txt files
4. Read xml files
5. Store data in this 6.
Learn to read development documents
7. File permissions