Android Program Development: (18) file-18.1 saved to internal storage devices

Source: Internet
Author: User

The sharedpreferences object allows you to save data of the "key-Value Pair" type, such as user ID, birthday, gender, and ID card number. However, sometimes you need to use a traditional file system to store data. For example, you may want to save an article, which will be displayed in your application. In the Android system, you can also use the java. Io package to implement this function.

In the Android system, the first method to save files is to store them to internal devices. The following shows how to save the string entered by the user book to an internal storage device.

1. Create a project, files.

2. Code in Main. xml.

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="Please enter some text" />    <EditText        android:id="@+id/txtText1"        android:layout_width="fill_parent"        android:layout_height="wrap_content" />    <Button        android:id="@+id/btnSave"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:onClick="onClickSave"        android:text="Save" />    <Button        android:id="@+id/btnLoad"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:onClick="onClickLoad"        android:text="Load" /></LinearLayout>

3. Code in filesactivity. java.

package net.manoel.Files;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import net.learn2develop.Files.R;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.EditText;import android.widget.Toast;public class FilesActivity extends Activity {EditText textBox;static final int READ_BLOCK_SIZE = 100;/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);textBox = (EditText) findViewById(R.id.txtText1);}public void onClickSave(View view) {String str = textBox.getText().toString();try{FileOutputStream fOut =openFileOutput("textfile.txt",MODE_WORLD_READABLE);                        OutputStreamWriter osw = newOutputStreamWriter(fOut);//---write the string to the file---osw.write(str);osw.flush(); osw.close();//---display file saved message---Toast.makeText(getBaseContext(),"File saved successfully!",Toast.LENGTH_SHORT).show();//---clears the EditText---textBox.setText("");}catch (IOException ioe){ioe.printStackTrace();}}public void onClickLoad(View view) {try{FileInputStream fIn = openFileInput("textfile.txt");InputStreamReader isr = new InputStreamReader(fIn);            char[] inputBuffer = new char[READ_BLOCK_SIZE];String s = "";int charRead;while ((charRead = isr.read(inputBuffer))>0){//---convert the chars to a String---String readString =String.copyValueOf(inputBuffer, 0,charRead);s += readString;inputBuffer = new char[READ_BLOCK_SIZE];}//---set the EditText to the text that has been // read---textBox.setText(s);Toast.makeText(getBaseContext(),"File loaded successfully!",Toast.LENGTH_SHORT).show();}catch (IOException ioe) {ioe.printStackTrace();}}}

4. Debug on the simulator.

5. Enter some strings and then press save.

6. If the file is successfully saved, "file saved successfully!" is displayed! . The string in edittext is cleared at the same time.

7. Press the load key and the string will appear again. This also proves that the string has been successfully saved to the file system.

Analysis:

To save a string to a file, use the fileoutputstream class. The openfileoutput () method opens a file for writing and specifies the corresponding mode. In this example, the mode_world_readable constant is used, which means the file can be read by other applications.

FileOutputStream fOut =openFileOutput("textfile.txt",MODE_WORLD_READABLE);

In addition to the mode_world_readable constant, there are also mode_private, mode_append, mode_world_writeable.

To convert a string stream into a word throttling, you need to use an outputstreamwriter class. during initialization, You need to input a fileoutputstream object:

OutputStreamWriter osw = newOutputStreamWriter(fOut);

Call the write () interface to write strings in the file. To ensure that all bytes are written to the file, call the flush () interface. Finally, call the close () interface to close the stream.

//---write the string to the file---osw.write(str);osw.flush(); osw.close();

The above is the write process. The read process is similar to this. I will not repeat it here. Refer to the following code.

public void onClickLoad(View view) {try{FileInputStream fIn = openFileInput("textfile.txt");InputStreamReader isr = new InputStreamReader(fIn);            char[] inputBuffer = new char[READ_BLOCK_SIZE];String s = "";int charRead;while ((charRead = isr.read(inputBuffer))>0){//---convert the chars to a String---String readString =String.copyValueOf(inputBuffer, 0,charRead);s += readString;inputBuffer = new char[READ_BLOCK_SIZE];}//---set the EditText to the text that has been // read---textBox.setText(s);Toast.makeText(getBaseContext(),"File loaded successfully!",Toast.LENGTH_SHORT).show();}catch (IOException ioe) {ioe.printStackTrace();}}

Finally, we use the ddms tool to check whether the file is successfully saved to an internal storage device.

You can see that the file is saved to the path data/net. Manoel. Files/files.

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.