An example of the save and read function of the Android implementation file _android

Source: Internet
Author: User
Tags gettext save file sqlite database

This article illustrates the saving and reading function of the Android implementation file. Share to everyone for your reference, specific as follows:

Note: There are Getfiledir () and Getcachedir () in the activity; method to obtain the current package file path from the current phone's storage space

Getfiledir ()-----/data/data/cn.xxx.xxx (current package)/files
Getcachedir ()-----/data/data/cn.xxx.xxx (current package)/cache

1. Write the file read and write function implementation class Fileservice

Package cn.android.service;
Import Java.io.ByteArrayOutputStream;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import Android.content.Context;
Import Android.util.Log; /** * File Save and read function implementation class * @author Administrator * * 2010-6-28 PM 08:15:18/public class Fileservice {public static final St
  Ring TAG = "Fileservice";
  private context;
  Gets the reference of the incoming context object public Fileservice {this.context = contexts; /** * Save File * * @param filename filename * @param content file * @throws Exception/public void Save (S) Tring filename, String content) throws Exception {//Because the page is entered with textual information, it is automatically added with the. txt suffix if the filename is not terminated with the. txt suffix name (!filename.end
   Swith (". txt")) {filename = filename + '. txt ';
   } byte[] buf = filename.getbytes ("iso8859-1");
   LOG.E (TAG, New String (buf, "utf-8"));
   FileName = new String (buf, "utf-8");
   LOG.E (TAG, fileName); Context.mode_private: For the default mode of operation, the file is private data and can only be accessed by the application itself, in which the written content overwrites the contents of the original file, if you want to append the newly written content to the original file. OKUsing Context.mode_append//context.mode_append: Mode will check whether the file exists, append content to the file, or create a new file.
   Context.mode_world_readable and context.mode_world_writeable are used to control whether other applications have permission to read and write to the file.
   Mode_world_readable: Indicates that the current file can be read by another application; Mode_world_writeable: Indicates that the current file can be written by another application.
   If you want the file to be read and written by another application, you can pass in://Openfileoutput ("Output.txt", context.mode_world_readable + context.mode_world_writeable); FileOutputStream fos = context.openfileoutput (fileName, context.)
   Mode_private);
   Fos.write (Content.getbytes ());
  Fos.close (); /** * Read File content * * @param filename filename * @return file content * @throws Exception/public String Read (stri
    ng filename) throws Exception {//Because the page input is text information, automatically add the. txt suffix if (!filename.endswith (". txt") when the filename is not terminated with the. txt suffix name.
   filename = filename + ". txt";
   } FileInputStream fis = Context.openfileinput (fileName);
   Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();
   byte[] buf = new byte[1024];
   int len = 0; Place the read data in memory---bytearrayoutputstream while(len = Fis.read (buf))!=-1)
   {baos.write (buf, 0, Len);
   } fis.close ();
   Baos.close ();
  Returns the data stored in memory return baos.tostring ();

 }
}

2. Writing activity classes:

Package cn.android.test;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.util.Log;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.EditText;
Import Android.widget.Toast;
Import Cn.android.service.FileService; The public class Testandroidactivity extends activity {/** called the ' when the ' is ' the activity ' is the ' the './/Created
  Like private fileservice Fileservice = new Fileservice (this);
  Defines the filename input box object in the View private EditText filenametext;
  Define the ContentText input box object in the View private EditText contenttext;
  Define a toast Hint object private Toast Toast;
  @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
  Setcontentview (R.layout.main);
  Get two input boxes and two button objects in the View Reference button button = (Button) This.findviewbyid (R.id.button);
  Button read = (button) This.findviewbyid (R.id.read);
  Filenametext = (edittext) This.findviewbyid (r.id.filename);
  ContentText = (edittext) This.findviewbyid (r.id.content); To protectSave button Add Save Event Button.setonclicklistener (new View.onclicklistener () {@Override public void OnClick (View v) {St
     Ring FileName = Filenametext.gettext (). toString ();
     String content = Contenttext.gettext (). toString ();
     When the file name is empty, the prompt user file name is empty and logs are logged. if (IsEmpty (fileName)) {toast = Toast.maketext (Testandroidactivity.this, R.string.empty_filename, Toast.length_long)
      ;
      Toast.setmargin (result_canceled, 0.345f);
      Toast.show ();
      LOG.W (Fileservice.tag, "The file name is empty");
     Return
     //When the contents of the file are empty, prompt the user for the contents of the file to be empty and log.
      if (IsEmpty (content)) {toast = Toast.maketext (Testandroidactivity.this, r.string.empty_content, Toast.length_long);
      Toast.setmargin (result_canceled, 0.345f);
      Toast.show ();
      LOG.W (Fileservice.tag, "The file content is empty");
     Return
      ///when the filename and content are not empty, invoke the Fileservice Save method//When successfully executed, prompt the user to save the success, and log//When an exception occurs, prompts the user to save the failure and logs a try { Fileservice.save (FileName, content);
      Toast = Toast.maketext (Testandroidactivity.this, r.string.success, Toast.length_long);
      Toast.setmargin (result_canceled, 0.345f);
      Toast.show ();
     LOG.I (Fileservice.tag, "The File Save successful");
      catch (Exception e) {toast = Toast.maketext (Testandroidactivity.this, R.string.fail, Toast.length_long);
      Toast.setmargin (result_canceled, 0.345f);
      Toast.show ();
     LOG.E (Fileservice.tag, "The File Save Failed");
  }
    }
  });
     Add read event Read.setonclicklistener for Read button (new View.onclicklistener () {@Override public void OnClick (View v) {
     Get the value String filename = Filenametext.gettext () in the File name input box. toString (); If the file name is empty, prompt the user for a filename and log if (IsEmpty (fileName)) {toast = Toast.maketext (Testandroidactivity.this, R.string.em
      Pty_filename, Toast.length_long);
      Toast.setmargin (result_canceled, 0.345f);
      Toast.show ();
      LOG.W (Fileservice.tag, "The file name is empty");
     Return }//Call FilEService Read method and puts the read content into the text content input box///If successful, prompts the user to read successfully and logs the log.
     If an exception message appears (for example: A file does not exist), prompts the user for a read failure and logs the log.
      try {contenttext.settext (Fileservice.read (fileName));
      Toast = Toast.maketext (Testandroidactivity.this, r.string.read_success, Toast.length_long);
      Toast.setmargin (result_canceled, 0.345f);
      Toast.show ();
     LOG.I (Fileservice.tag, "The file read successful");
      catch (Exception e) {toast = Toast.maketext (Testandroidactivity.this, R.string.read_fail, Toast.length_long);
      Toast.setmargin (result_canceled, 0.345f);
      Toast.show ();
     LOG.E (Fileservice.tag, "The file read failed");
  }
    }
  }); //Write a IsEmpty method to determine whether the string is empty private Boolean isempty (string s) {if (s = = NULL | |
  '. Equals (S.trim ()) {return true;
  return false;

 }
}

3. File layout file: Main.xml

<?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/filena Me "/> <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" Andro id:text= "@string/content"/> <edittext android:layout_width= "Fill_parent" android:layout_height=
  Ent "android:minlines=" 3 "android:id=" @+id/content "/> <linearlayout android:orientation=" Horizontal " Android:layout_width= "Fill_parent" android:layout_height= "fill_parent" > <button android:layout_width= "WRAP_" Content "Android:layout_height= "Wrap_content" android:id= "@+id/button" android:text= "@string/save"/> <button 
   T_width= "Wrap_content" android:layout_height= "wrap_content" android:id= "@+id/read" android:text= "@string/read"

 /> </LinearLayout> </LinearLayout>

PS: Because I am testing this feature when I found that the file name can not be used in Chinese (sdk2.2 + simulator), if there is a master inadvertently browsing this article, can give advice on this issue, I would be grateful. Oh.

For more information on Android-related content readers can view the site: "Android file Operation tips Summary", "Android Programming activity Operation Tips Summary", "Android View Overview", " Android Operation SQLite Database skills Summary, "Android operation JSON format Data Skills summary", "Android Database Operation skills Summary", "Android programming development of SD card Operation Summary", "Android Development introduction and Advanced Course", A summary of Android resource operations tips and a summary of the usage of Android controls

I hope this article will help you with the Android program.

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.