Android development path 10 (file read/write), android path
1. Data Storage instance for files in Android (Save the files to the bucket that comes with your mobile phone ):
① MainActivity. java
Public class MainActivity extends Activity implements OnClickListener {
Private Button mButton;
Private EditText etFilename;
Private EditText etFileContent;
/**
* File storage:
* Step 1: Create a layout file (including entering the file name and content );
* Step 2: Obtain the control object in our main Activity and set a listener for the button to complete the operations of obtaining the filled content and saving the file.
* Step 3: We usually place the business class in the project to the service layer. Therefore, we need to create a business class and write the file.
*/
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_main );
MButton = (Button) findViewById (R. id. button );
MButton. setOnClickListener (this );
}
@ Override
Public void onClick (View v ){
EtFilename = (EditText) findViewById (R. id. filename );
EtFileContent = (EditText) findViewById (R. id. filecontent );
String filename = etFilename. getText (). toString ();
String filecontent = etFileContent. getText (). toString ();
FileService service = new FileService (getApplicationContext ());
Try {
Service. save (filename, filecontent );
Toast. makeText (getApplicationContext (), R. string. success, Toast. LENGTH_LONG). show ();
} Catch (Exception e ){
Toast. makeText (getApplicationContext (), R. string. fail, Toast. LENGTH_LONG );
E. printStackTrace ();
}
}
}
② FileService. java
Public class FileService {
Private Context context;
Public FileService (Context context ){
This. context = context;
}
// Save the file to the internal storage of the mobile phone
Public void save (String filename, String filecontent) throws Exception {
/**
* FileOutputStream: file output stream
* OpenFileOutput () method:
* Parameter 1. Name of the file to be saved; parameter 2. Operation Mode of saving the file
* Here we use the private operation mode, that is, the created file can only be accessed by this application, and other applications cannot access this file,
* In addition, if a file is created in the private operation mode, the content written to the file overwrites the content of the source file.
*/
FileOutputStream outputStream = context. openFileOutput (filename, Context. MODE_PRIVATE );
OutputStream. write (filecontent. getBytes ());
OutputStream. close ();
}
// Read files stored in the mobile phone
Public String read (String filename) throws Exception {
// FileInputStream: file input stream
FileInputStream inputStream = context. openFileInput (filename );
ByteArrayOutputStream outputStream = new ByteArrayOutputStream ();
Byte [] buffer = new byte [1024];
Int len = 0;
While (len = inputStream. read (buffer ))! =-1 ){
OutputStream. write (buffer, 0, len );
}
Byte [] data = outputStream. toByteArray ();
Return new String (data );
}
}
③ Unit test class: FileServiceTest. java
Public class FileServiceTest extends AndroidTestCase {
Private static final String TAG = "FileServiceTest ";
// Unit test method testSave () is used to test whether the save (String filename, String filecontent) method is correct.
Public void testSave () throws Throwable {
FileService service = new FileService (this. getContext ());
Service. save ("456.txt"," sdfdgsdfasd ");
Log. I (TAG, "successful ");
}
// Unit test: The testRead () method is used to test whether our read (String filename) method is wrong.
Public void testRead () throws Throwable {
FileService service = new FileService (this. getContext ());
String result = service. read ("123.txt ");
Log. I (TAG, result );
}
}
④ List file AndroidManifest. xml
<? Xml version = "1.0" encoding = "UTF-8"?>
<Manifest xmlns: android = "http://schemas.android.com/apk/res/android"
Package = "com. rookie. test1"
Android: versionCode = "1"
Android: versionName = "1.0" type = "codeph" text = "/codeph">
<Uses-sdk
Android: minSdkVersion = "10"
Android: targetSdkVersion = "10"/>
<! -- Unique identifier of a unit test -->
<Instrumentation
Android: name = "android. test. InstrumentationTestRunner"
Android: targetPackage = "com. rookie. test1"
Android: label = "testapp"/>
<Application
Android: allowBackup = "true"
Android: icon = "@ drawable/ic_launcher"
Android: label = "@ string/app_name"
Android: theme = "@ style/AppTheme">
<! -- Add a unit test environment -->
<Uses-library android: name = "android. test. runner"/>
<Activity
Android: name = ". MainActivity"
Android: label = "@ string/app_name">
<Intent-filter>
<Action android: name = "android. intent. action. MAIN"/>
<Category android: name = "android. intent. category. LAUNCHER"/>
</Intent-filter>
</Activity>
</Application>
</Manifest>
⑤ Layout file activity_main.xml (omitted)
2. Data Storage instance of files in Android (save data to the SD card of the mobile phone)
To save data to the SD card, you must first set the relevant permissions in the list file,
For example:
<! -- Create and delete files on the SD card -->
<Uses-permission android: name = "android. permission. MOUNT_UNMOUNT_FILESYSTEMS"/>
<! -- Permission to write data to the SD card -->
<Uses-permission android: name = "android. permission. WRITE_EXTERNAL_STORAGE"/>
Then we need to add a method for FileService. java in the above instance,
Used to save files to mobile sdcard
Public void saveToSDCard (String filename, String filecontent) throws Exception {
File file = new File (Environment. getExternalStorageDirectory (), filename );
FileOutputStream outputStream = new FileOutputStream (file );
OutputStream. write (filecontent. getBytes ());
OutputStream. close ();
}
Then we need to rewrite the previously rewritten onClick () method in the MainActivity. java file:
@ Override
Public void onClick (View v ){
EtFilename = (EditText) findViewById (R. id. filename );
EtFileContent = (EditText) findViewById (R. id. filecontent );
String filename = etFilename. getText (). toString ();
String filecontent = etFileContent. getText (). toString ();
FileService service = new FileService (getApplicationContext ());
Try {
// Determine whether the SD card exists and can be read/written
If (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED )){
Service. saveToSDCard (filename, filecontent );
Toast. makeText (getApplicationContext (), R. string. success, Toast. LENGTH_LONG). show ();
} Else {
Toast. makeText (getApplicationContext (), R. string. sd_error, Toast. LENGTH_LONG). show ();
}
} Catch (Exception e ){
Toast. makeText (getApplicationContext (), R. string. fail, Toast. LENGTH_LONG );
E. printStackTrace ();
}
}
So far, we have completed the functional code for writing files to the SD card. Let's try it!