In this blog, we want to implement "new file" and "Read File" in Android:
Target interface:
After entering the file name, enter the file contents, click Save, can be saved as a document
First, let's start with an Android Project project, project name: File.
Then, we need to implement the interface in the target view first:
Edit Strings.xml File:
<?xml version= "1.0" encoding= "Utf-8"?><resources> <string name= "Hello" >hello world, fileactivity!</string> <string name= "app_name" > File operations </string> <string name= "filename "> File name </string><string name=" filecontent "> File contents </string><string name=" button "> Save </ String><string name= "Success" > Save complete </string><string name= "fail" > Save failed </string></ Resources>
Editor: Main.xml File:
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "android:orientation=" vertical "android:layout_width=" fill_parent "android:layout_height=" Fill_parent " > <textview android:layout_width= "fill_parent" android:layout_height= "Wrap_content" Android : text= "@string/filename"/> <edittext android:layout_width= "Fill_parent" android:layout_height= "Wrap_content" android:id= "@+id/filename"/> <textview android:layout_width= "Fill_parent" android:layout_height= "Wrap_content" android:text= "@string/filecontent"/> <edittext Android:layout_width= "Fill_parent" android:layout_height= "wrap_content" android:id= "@+id/filecontent" /> <button android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Androi d:text= "@string/button" AndroId:id= "@+id/button"/></linearlayout>
As a result, we have finished building the interface, and the next step is to write the Java code (which is no longer described in detail in the interface authoring process).
Then, we want to edit the Fileactivity.java (the code is specifically explained in the program):
Package Cn.itcast.files;import Cn.itcast.fservice.fileservice;import Android.app.activity;import android.os.Bundle ; Import Android.view.view;import android.widget.button;import android.widget.edittext;import android.widget.Toast; public class Fileactivity extends activity {/** Called when the activity is first created. */@Override Public V OID onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main); Implement the Jump button button for the layout page = (button) This.findviewbyid (R.id.button); Gets the button property Button.setonclicklistener (New Buttonclicklistener ()); Set Listener for Button}/** * button click event Listener Implementation * @author HC * */private Final class Buttonclicklistener Implements view.onclicklistener{@Overridepublic void OnClick (View v) {//Generate default method EditText Filenametext = (EditText) Findviewbyid (R.id.filename); Get the file name input Box object EditText ContentText = (EditText) Findviewbyid (r.id.filecontent); Get the file Contents input Box object string filename =Filenametext.gettext (). toString (); Gets the input "file name" String content = Contenttext.gettext (). toString (); Get the input "file content"//new a Fileservice object, Getapplicationcontext () returns the application context, the lifecycle is the entire application, and the application destroys it to destroy fileservice service = new Fileservice (Getapplicationcontext ()); try {service.save (filename,content);//Call the Save () method to save the file Toast.maketext (Getapplicationcontext (), r.string.success, 1). Show (); Call a Toast to render a "save complete" message} catch (Exception e) {toast.maketext (Getapplicationcontext (), R.string.fail, 1). Show ();// Call Toast object to render a "save failed" message E.printstacktrace ();}} } }
In Fileactivity.java we used a class Fileservice.java, which provided a write file written () and read the file reading () method.
Therefore, we need to create a Fileservice.java class:
Package Cn.itcast.fservice;import Java.io.bytearrayoutputstream;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Android.content.context;public class Fileservice {private Context context;public Fileservice (context context) {super () ; this.context = context;} /** * Write file and close file * @param content Write contents * @param outstream output stream * @throws ioexception */private void Write (String content, Fi Leoutputstream OutStream) throws IOException {Outstream.write (content.getbytes ()); Outstream.close ();} /** * Save file * @param filename File name * @param content file contents * @throws Exception */public void Save (string filename, String Co Ntent) throws Exception {//Private mode of operation: The file created can only be accessed by the app and cannot be accessed by other apps. In addition, a file created with private operation mode overwrites the contents of the source file with the contents of the FileOutputStream OutStream = Context.openfileoutput (filename,context.mode_ PRIVATE); Open output stream with private operation mode write (content, outstream);} /** * Read File contents * @param filename File name * @return File contents * @throws Exception */public String Read (STring filename) throws Exception{fileinputstream instream = context.openfileinput (filename); Bytearrayoutputstream OutStream = new Bytearrayoutputstream (); byte[] buffer = new Byte[1024];int len = 0;//Read return-1, unread read back How much data while (len = instream.read (buffer))! =-1) {outstream.write (buffer, 0, Len);} byte[] data = Outstream.tobytearray (); return new String (data);}}
When we get here, we've implemented the functionality, and then we're going to deploy the project to the Android simulator,
Test it:
As you can see, our file is already saved, and here we need to find out where this file was saved.
First, we need to open the File Explorer view:
We can find the Test.txt file in Data->data->cn.itcast.files (this is the project's package)->files this directory, and then we export it to the desktop
You can see that the content inside is what we enter.
Speaking of which, the preservation of the file has been introduced, and then we want to introduce the file read:
We need to set up a test file and build a test file that needs to be configured Androidmanifest.xml (see the Android Development series (iv) for the configuration of this file, which will no longer be configured)
We set up a test class: Fileservicetest.java (Inheriting the Androidtestcase Class):
Package Cn.itcast.test;import Cn.itcast.fservice.fileservice;import Android.test.androidtestcase;import Android.util.log;public class Fileservicetest extends Androidtestcase {private static final String TAG = "Fileservicetest "; Set a tagpublic void Testread () throws Throwable{fileservice service = new Fileservice (This.getcontext ()); String result = Service.read ("Test.txt"); Read File test.txtlog.i (TAG, result); Give the contents of the resulting document to tag. Then we can see it in the Logcat interface.}}
Can be viewed as follows:
Android Development Series (V): Saving and reading files in Android apps