Android Development Series (5): storage and reading of files in Android applications, android Development

Source: Internet
Author: User
Tags readfile

Android Development Series (5): storage and reading of files in Android applications, android Development

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


First, create an Android Project named File.

Then, we need to first implement the interface in the target view:

Edit the strings. xml file:

<? Xml version = "1.0" encoding = "UTF-8"?> <Resources> <string name = "hello"> Hello World, FileActivity! </String> <string name = "app_name"> file operation </string> <string name = "filename"> file name </string> <string name = "filecontent"> file content </string> <string name = "button"> saved </string> <string name = "success"> saved </string> <string name = "fail"> failed to save </string> </resources>
Edit: 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"       android:text="@string/button"       android:id="@+id/button"       /></LinearLayout>
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:





In android development, how does one save a string in txt format and coexist with the SD card? Are there read problems?

/**
* Save the file
* @ Param toSaveString
* @ Param filePath
*/
Public static void saveFile (String toSaveString, String filePath)
{
Try
{
File saveFile = new File (filePath );
If (! SaveFile. exists ())
{
File dir = new File (saveFile. getParent ());
Dir. mkdirs ();
SaveFile. createNewFile ();
}

FileOutputStream outStream = new FileOutputStream (saveFile );
OutStream. write (toSaveString. getBytes ());
OutStream. close ();
} Catch (FileNotFoundException e)
{
E. printStackTrace ();
} Catch (IOException e)
{
E. printStackTrace ();
}
}

/**
* Reading file content
* @ Param filePath
* @ Return File Content
*/
Public static String readFile (String filePath)
{
String str = "";
Try
{
File readFile = new File (filePath );
If (! ReadFile. exists ())
{
Return null;
}
FileInputStream inStream = new FileInputStream (readFile );
ByteArrayOutputStream stream = new ByteArrayOutputStream ();
Byte [] buffer = new byte [1024];
Int length =-1;
While (length = inStream. read (buffer ))! =-1)
{
Stream. write (buffer, 0, length );
}
Str = stream. toString ();
Stream. close ();
InStream. close ();
Return str;
}
Catch (FileNotFoundException e)
{
E. printStackTrace ();
Return null;
}
Catch (IOException e)
{
E. printStackTrace ();
Return null;
}
}... Remaining full text>

How to Write configuration files for android Development

If you want to modify an xml file, you can use the SAX or DOM method to read the xml file to be modified, and then use the corresponding interface to modify and save it. However, this method is not recommended, the reason is that, according to the Android design philosophy, all resources stored in the res directory of the project should be immutable and independent resources. You can use this method as needed: 1. Define all values that may be changed in strings. xml. 2. When you need to change the code, set it again, such as setText. This method is a common method. You do not need to restart the program if the setting takes effect immediately. If you do not want to use this method, but want to use the configuration file method, you can use sharedpreferences to save/read the corresponding configuration, and then use setText and other methods to apply the configuration to the program, sharedpreferences stores the configuration in the/data/<package name>/shares_prefs directory in xml format.

Hope to help you.

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.