Android学习之3:文件的保存与读取

来源:互联网 发布:社会学stata数据库 编辑:程序博客网 时间:2024/05/21 17:57

1. 在strings.xml中配置如下:

这里是定义了几个好比string类型的变量,可以用在布局配置文件中,来显示比如按钮上的文字,或者是标题名称等等。。。

1
2
3
4
5
<string name="title">标题</string>
<string name="content">内容</string>
<string name="saveButton">保存</string>
<string name="success">保存成功</string>
<string name="fail">保存失败</string>

2. 在activity_main.xml中配置如下app界面布局

【这里是线性布局】

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

3. 在MainActivity.java中实现如下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.example.filesaveandread;
                                                          
import java.io.IOException;
                                                          
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
                                                          
public class MainActivity extends Activity {
                                                          
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 通过按钮id找到名称为saveButton的按钮
        Button saveButton = (Button) this.findViewById(R.id.saveButton);
        // 为该按钮设定一个按钮按下Listener监听事件,通过该监听事件
        // 实现当按钮按下时,触发ButtonClickListener中的onClick方法来实现相关功能
        saveButton.setOnClickListener(new ButtonClickListener());
    }
                                                              
    // 自定义成员内部类,实现按钮按下相关功能
    private final class ButtonClickListener implements OnClickListener {
                                                          
        @Override
        public void onClick(View v) {
            // 通过相关id找到title和content输入框
            EditText titleText = (EditText) findViewById(R.id.title);
            EditText contentText = (EditText) findViewById(R.id.content);
            // 获取其输入框中的内容
            String title = titleText.getText().toString();
            String content = contentText.getText().toString();
            FileService fileService = new FileService(getApplicationContext());
            try {
                // 调用FileService中save方法来保存相关输入内容
                fileService.save(title, content);
                // 设置保存成功是的提示信息为success中的内容,
                Toast.makeText(getApplicationContext(), R.string.success, 1).show();
            catch (IOException e) {
                // 若保存失败则显示发送失败fail
                Toast.makeText(getApplicationContext(), R.string.fail, 1).show();
                e.printStackTrace();
            }
        }
    }
}

4. 保存信息至文件中:FileService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.example.filesaveandread;
                                                       
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
                                                       
import android.content.Context;
                                                       
public class FileService {
                                                           
    private Context context;
                                                           
    public FileService(Context context) {
        this.context = context;
    }
                                                       
    /**
     * 保存文件
     * @param title
     * @param content
     * @throws IOException
     */
    public void save(String title, String content) throws IOException {
        FileOutputStream out = context.openFileOutput(title, Context.MODE_PRIVATE);
        out.write(content.getBytes());
        out.close();
    }
}

5. 从文件中读取内容

这里我们用junit来测试读取功能

    (1). 在 4 中的文件中加入如下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
     * 读取文件
     * @param fileName
     * @return
     * @throws IOException
     */
    public String read(String fileName) throws IOException {
        FileInputStream input = context.openFileInput(fileName);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length = 0;
        while((length = input.read(buffer)) != -1) {
            // 从文件中读取出来之后,放入到内存中去
            out.write(buffer, 0, length);
        }
        byte[] bytes = out.toByteArray();
        return new String(bytes);
    }

    (2). 创建一个普通类,让其继承 extends AndroidTestCase

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.test.FileService;
                                        
import java.io.IOException;
                                        
import com.example.filesaveandread.FileService;
                                        
import android.test.AndroidTestCase;
import android.util.Log;
                                        
public class testFileService extends AndroidTestCase {
                                            
    private final String TAG = "FileServiceTest";
                                            
    public void testRead() throws IOException {
        FileService fileService = new FileService(this.getContext());
        String data = fileService.read("zhidanfeng");
        Log.i(TAG, data);
    }
}

    (3). 要想改单元测试有效,需要在AndroidManifest.xml中配置如下配置:

在<application ..... 下面配置如下,记住是在<application下面而不是<activity下面

1
<uses-library android:name="android.test.runner" />

之后在<application ..... 外面那层配置如下:

1
2
3
<instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="com.example.filesaveandread" />

    (4)选中testRead,右键 RunAs -> Android JUnit Test 即可运行该测试方法,可以在LogCat中看到输出内容


备注:保存的信息可以在File Explorer栏里面找到,data --> data --> 文件所在包名 --> files

。如果你的eclipse一开始没有File Explorer的话,可以这样将其显示出来:Windows --> Show View --> Others , 搜索File Explorer既可以将其调出来

OK,该篇内容完了,应该没有漏掉配置吧

源文件下载地址:

http://pan.baidu.com/share/link?shareid=4059597539&uk=1779741788

我的点点博客源博文地址:http://zhidanfeng.diandian.com/post/2013-07-02/40050328800

原创粉丝点击