Android Development Series (5): Saving and reading files in Android applications

Source: Internet
Author: User

Android Development Series (5): Saving and reading files in Android applications

In this blog, we want to implement "new file" and "Read File" in Android ":

Target Interface:

After entering the file name, enter the file content and click Save to save it as a document


<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + ytfPyKOsztLDx8/release/o6zP7sS/w/release/IyrXP1sS/serK08281tC1xL3nw + ajuw.vcd4kpha + release/release = "brush: java;"> Hello World, FileActivity! File Operations File Name File Content Save Saved Failed to save Edit: main. xml file:

 
     
          
         
         
         
  
 
As a result, we have completed the interface construction, and the next step is to write java code (the interface compilation process is not described in detail ).


Then, edit FileActivity. java (the code is 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 void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); // implement the jump Button = (button) this. findViewById (R. id. button); // obtain the Button attribute. setOnClickListener (new ButtonClickListener (); // set the listener for the Button}/*** Button click event listener implementation * @ author hc **/private final class ButtonClickListener implements View. onClickListener {@ Overridepublic void onClick (View v) {// generate the default method EditText filenameText = (EditText) findViewById (R. id. filename); // obtain the EditText contentText = (EditText) findViewById (R. id. filecontent); // obtain the object String filename = filenameText in the "file content" input box. getText (). toString (); // obtain the input "file name" String content = contentText. getText (). toString (); // get the input "file content" // a new FileService object, getApplicationContext () returns the context of the application, and the lifecycle is the entire application, the application destroys 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 present a "saved" message} catch (Exception e) {Toast. makeText (getApplicationContext (), R. string. fail, 1 ). show (); // call the Toast object to display a message e. printStackTrace ();}}}}


In FileActivity. java, we use FileService. java, which provides the write () and read () methods for writing files.

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 content * @ param outStream output stream * @ Throws IOException */private void write (String content, FileOutputStream outStream) throws IOException {outStream. write (content. getBytes (); outStream. close ();}/*** save file * @ param filename file name * @ param content File content * @ throws Exception */public void save (String filename, String content) throws Exception {// Private operation mode: The created file can only be accessed by this application, and other applications cannot access this file. // In addition, if the file is created in the private operation mode, the content in the written file overwrites the content of the source file FileOutputStream outStream = context. openFileOutput (filename, Context. MODE_PRIVATE); // use the private operation mode to open the output stream write (content, outStream );} /*** read File Content * @ param filename file name * @ return file content * @ throws Exception */public String read (String filename) throws Exception {FileInputStream inStream = context. openFileInput (filename); ByteArrayOutputStream outStream = new ByteArrayOutputStre Am (); byte [] buffer = new byte [1024]; int len = 0; // after reading, return-1, the number of data read while (len = inStream. read (buffer ))! =-1) {outStream. write (buffer, 0, len);} byte [] data = outStream. toByteArray (); return new String (data );}}

Now, we have implemented the function. Next, we will deploy the project to the Android simulator,
Test:


We can see that the file is saved. here we need to find out where the file is saved.


First, open the File Explorer View:


We can find the test.txt file in the data-> cn. itcast. files (this is the project package)-> files directory, and export it to the desktop.

We can see that the content inside is what we enter.


Here, the storage of the file has been introduced. Next we will introduce the reading of the file:

We need to create a test file. To create a test file, we need to configure AndroidManifest. xml first. (For details about the configuration of this file, see Android Development Series (4). This will not continue to be configured)

Let's create 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 the file Test.txt Log. I (TAG, Result); // deliver the result of the obtained file to the TAG. Then we can see it in the LogCat interface }}
You can see the following:




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.