文件保存与读取

一、界面

1.最终要实现的界面:

2.界面实现:

activity_main.xml:

 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     android:orientation="vertical"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5        >
 6 
 7     <TextView
 8         android:layout_width="match_parent"
 9         android:layout_height="wrap_content"
10         android:text="@string/filename" />
11     
12     <EditText 
13         android:layout_width="match_parent"
14         android:layout_height="wrap_content"
15         android:id="@+id/filename"/>
16     
17     <TextView
18         android:layout_width="match_parent"
19         android:layout_height="wrap_content"
20         android:text="@string/filecontent" 
21         />
22     
23     <EditText 
24         android:layout_width="match_parent"
25         android:layout_height="wrap_content"
26         android:id="@+id/filecontent"
27         android:minLines="3"
28         />
29     
30     <Button 
31         android:layout_width="wrap_content"
32         android:layout_height="wrap_content"
33         android:text="@string/button"
34         android:id="@+id/button"
35         />
36 
37 </LinearLayout>

string.xml:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <resources>
 3 
 4     <string name="app_name">文件操作</string>
 5     <string name="filename">文件名称</string>
 6     <string name="filecontent">文件内容</string>
 7     <string name="button">保存</string>
 8     <string name="success">保存完成</string>
 9     <string name="fail">保存失败</string>
10     <string name="hello_world">Hello world!</string>
11     <string name="action_settings">Settings</string>
12 
13 </resources>

二、代码实现

MainActivity.java:

 1 package com.example.file;
 2 
 3 import com.example.service.FileService;
 4 
 5 import android.app.Activity;
 6 import android.os.Bundle;
 7 import android.view.Menu;
 8 import android.view.MenuItem;
 9 import android.view.View;
10 import android.view.View.OnClickListener;
11 import android.widget.Button;
12 import android.widget.EditText;
13 import android.widget.Toast;
14 
15 public class MainActivity extends Activity {
16 
17     private EditText filename;
18     private EditText filecontent;
19     
20     @Override
21     protected void onCreate(Bundle savedInstanceState) {
22         super.onCreate(savedInstanceState);
23         setContentView(R.layout.activity_main);
24         
25         Button button = (Button)findViewById(R.id.button);
26         button.setOnClickListener(new ButtonOnClickListener());
27         
28         filename = (EditText)findViewById(R.id.filename);
29         filecontent = (EditText)findViewById(R.id.filecontent);
30     }
31  
32     private final class ButtonOnClickListener implements OnClickListener
33     {
34 
35         @Override
36         public void onClick(View v) {
37             String filenameText = filename.getText().toString();
38             String filecontentText = filecontent.getText().toString();
39             //实现文件保存
40             FileService service = new FileService(getApplicationContext());
41             try {
42                 service.save(filenameText,filecontentText);
43                 Toast.makeText(getApplicationContext(), R.string.success, 1).show();
44             } catch (Exception e) {
45                 Toast.makeText(getApplicationContext(), R.string.fail, 1).show();
46                 e.printStackTrace();
47             }
48             
49         }
50         
51     }
52 }

FileService.java:

(1)

 1 package com.example.service;
 2 
 3 import java.io.FileOutputStream;
 4 
 5 import android.content.Context;
 6 
 7 public class FileService {
 8 
 9     private Context context;//要给它赋值,否则会出现空指针错误!
10     //赋值方式有两种:1.通过set方法给其赋值 2.通过一个构造器给其赋值,选2方式防止忘记!
11     public FileService(Context context) {
12         super();
13         this.context = context;
14     }
15     /**
16      * 保存文件
17      * @param filenameText 文件名称,不带路径
18      * @param filecontentText 文件内容
19      */
20     public void save(String filenameText, String filecontentText) throws Exception{
21         // IO j2ee
22         //1.首先得到文件的输出流对象
23         //MODE_PRIVATE:私有操作模式,创建出来的文件只能被本应用访问,其他应用无法访问,另外采用私有操作模式创建的文件,写入文件中的内容会覆盖原文件内容
24         FileOutputStream outStream = context.openFileOutput(filenameText,Context.MODE_PRIVATE);//mode:追加、覆盖;访问权限
25         //写入数据:数据是以二进制形式写入到文件中的
26         outStream.write(filecontentText.getBytes());
27         outStream.close();
28     }
29 
30 }

(2)在(1)的基础上加入文件读取的内容

 1 package com.example.service;
 2 
 3 import java.io.ByteArrayOutputStream;
 4 import java.io.FileInputStream;
 5 import java.io.FileOutputStream;
 6 
 7 import android.content.Context;
 8 
 9 public class FileService {
10 
11     private Context context;//要给它赋值,否则会出现空指针错误!
12     //赋值方式有两种:1.通过set方法给其赋值 2.通过一个构造器给其赋值,选2方式防止忘记!
13     public FileService(Context context) {
14         super();
15         this.context = context;
16     }
17     /**
18      * 保存文件
19      * @param filenameText 文件名称,不带路径
20      * @param filecontentText 文件内容
21      */
22     public void save(String filenameText, String filecontentText) throws Exception{
23         // IO j2ee
24         //1.首先得到文件的输出流对象
25         //MODE_PRIVATE:私有操作模式,创建出来的文件只能被本应用访问,其他应用无法访问,另外采用私有操作模式创建的文件,写入文件中的内容会覆盖原文件内容
26         FileOutputStream outStream = context.openFileOutput(filenameText,Context.MODE_PRIVATE);//mode:追加、覆盖;访问权限
27         //写入数据:数据是以二进制形式写入到文件中的
28         outStream.write(filecontentText.getBytes());
29         outStream.close();
30     }
31     
32     /**
33      * 读取文件内容
34      * @param filename 文件名称
35      * @return 文件内容
36      * @throws Exception 
37      */
38     public String read(String filename) throws Exception
39     {
40         FileInputStream inStream = context.openFileInput(filename);//默认路径与输出流一致
41         ByteArrayOutputStream outStream = new ByteArrayOutputStream();
42         byte[] buffer = new byte[1024];
43         int len = 0;
44         while((len = inStream.read(buffer))!=-1){//读完返回-1;未读完返回读取的数据长度
45             outStream.write(buffer, 0, len); 
46         }
47         byte[] data = outStream.toByteArray();//得到内存中的所有数据
48         return new String(data);
49     }
50 
51 }

三、对文件读取进行单元测试

1.搭建单元测试环境

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 3     package="com.example.file"
 4     android:versionCode="1"
 5     android:versionName="1.0" >
 6 
 7     <uses-sdk
 8         android:minSdkVersion="14"
 9         android:targetSdkVersion="21" />
10 
11     <application
12         android:allowBackup="true"
13         android:icon="@drawable/ic_launcher"
14         android:label="@string/app_name"
15         android:theme="@style/AppTheme" >
16         <activity
17             android:name=".MainActivity"
18             android:label="@string/app_name" >
19             <intent-filter>
20                 <action android:name="android.intent.action.MAIN" />
21 
22                 <category android:name="android.intent.category.LAUNCHER" />
23             </intent-filter>
24         </activity>
25         
26         <uses-library android:name="android.test.runner" />
27         
28     </application>
29     
30     <instrumentation android:name="android.test.InstrumentationTestRunner"
31         android:targetPackage="com.example.file"
32         android:label="Test for My App"
33         >
34     </instrumentation>
35 
36 </manifest>

2.编写单元测试代码

FileServiceTest.java:

 1 package com.example.test;
 2 
 3 import com.example.service.FileService;
 4 
 5 import android.content.Context;
 6 import android.test.AndroidTestCase;
 7 import android.util.Log;
 8 
 9 public class FileServiceTest extends AndroidTestCase {
10     private static final String TAG = "FileServiceTest";
11     public void testRead() throws Throwable
12     {
13         FileService service = new FileService(this.getContext());
14         String result = service.read("jtt.txt");//之前保存过的文件
15         Log.i(TAG, result);
16     }
17 }

3.对testRead()方法进行单元测试

注:

1.当我们使用Context类中的openFileOutput()方法来保存文件的时候,会默认保存在/data/data/<package name>/files路径下。

2.使用真机时,/data/...  路径下的文件我们是看不到的,因为没有root权限,除非手机为eng版本,或者用虚拟机测试。

原文地址:https://www.cnblogs.com/ttzm/p/7225664.html