手机的sd卡的写入和读取数据的方

我们要实现的是:往输入框输入数据,点击一个写入按钮,将输入框内的数据写入到sd卡上,在点击读取按钮,则将sd卡上只等的文件名称内的数据显示到一个textView上。

首先,看一下XML文件,很简单,只有两个按钮,一个输入框,和一个文本控件;

保存的数据可以到mnt/sdcard/下查看

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="59dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="46dp"
        android:text="写入" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button1"
        android:layout_alignBottom="@+id/button1"
        android:layout_alignRight="@+id/editText1"
        android:text="读取" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/button2"
        android:layout_marginBottom="14dp"
        android:layout_toRightOf="@+id/button1"
        android:text="TextView" />

</RelativeLayout>

  然后是自己新建的一个功能类FileService,主要负责往sd卡上读取和写入数据。

package com.example.sdcord;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.os.Environment;

/**
 * 主要用于往sd卡上读取和写入数据
 * 
 * @author Administrator
 * 
 */
public class FileService {

	private Context context;

	public FileService(Context context) {
		this.context = context;
	}

	/**
	 * 写入数据
	 * 
	 * @param fileName
	 *            文件名称
	 * @param context
	 *            文件内容
	 * @return 返回值是false则写入数据失败,反之则成功
	 */
	public boolean saveFile(String fileName, String context) {
		boolean flag = false;
		FileOutputStream fileOutputStream = null;
		// getExternalStorageDirectory():返回扩展存储卡的目录
		File file = new File(Environment.getExternalStorageDirectory(),
				fileName);
		// getExternalStorageState():返回扩展存储卡的当前状态,调用此方法,将会
		// 返回一个String类型状态值,如果返回的状态和Environment.MEDIA_MOUNTED(已经挂载并且拥有可读可写权限)
		//的值一样的话,说明当前的sd卡可以进行操作
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			try {
				fileOutputStream = new FileOutputStream(file);
				fileOutputStream.write(context.getBytes());
				flag = true;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (fileOutputStream != null) {
				}
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return flag;
	}

	/**
	 * 
	 * @param fileName 文件名稱
	 * @return			以字符串表現形式返回讀取到的數據
	 */
	public String getFile(String fileName) {
		FileInputStream fileInputStream = null;
		//缓冲的流,与磁盘无关,所以不需要关闭
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		File file = new File(Environment.getExternalStorageDirectory(),
				fileName);
		//判断sd卡是否可用
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			try {
				fileInputStream = new FileInputStream(file);
				int len = 0;
				byte[] data = new byte[1024];
				while ((len = fileInputStream.read(data)) != -1) {
					output.write(data, 0, len);
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (fileInputStream != null) {
					try {
						fileInputStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}

		}

		return new String(output.toByteArray());

	}
}

  接着是activity类,

 1 package com.example.sdcord;
 2 
 3 import android.app.Activity;
 4 import android.os.Bundle;
 5 import android.text.Editable;
 6 import android.view.Menu;
 7 import android.view.View;
 8 import android.view.View.OnClickListener;
 9 import android.widget.Button;
10 import android.widget.EditText;
11 import android.widget.TextView;
12 
13 public class MainActivity extends Activity implements OnClickListener{
14     
15     private Button btn1;
16     private Button btn2;
17     private TextView textView;
18     private EditText editText;
19 
20     @Override
21     protected void onCreate(Bundle savedInstanceState) {
22         super.onCreate(savedInstanceState);
23         setContentView(R.layout.activity_main);
24         
25         btn1 = (Button) findViewById(R.id.button1);
26         btn2 = (Button) findViewById(R.id.button2);
27         textView = (TextView) findViewById(R.id.textView1);
28         editText = (EditText) findViewById(R.id.editText1);
29         
30         btn1.setOnClickListener(this);
31         btn2.setOnClickListener(this);
32         
33     }
34     
35     public void onClick(View view){
36         switch(view.getId()){
37         case R.id.button1:
38             String data1 = editText.getText().toString();
39             savaFile("test.txt",data1);
40             break;
41         case R.id.button2:
42             String data2 = readFile("test.txt");
43             textView.setText(data2);
44             break;
45         }
46     }
47     
48     public void savaFile(String dir,String data){
49         FileService fileService = new FileService(this);
50         fileService.saveFile(dir,data);
51     }
52     
53     public String readFile(String fileName){
54         FileService fileService = new FileService(this);
55         String data = fileService.getFile(fileName);
56         return data;
57     }
58 
59 
60     @Override
61     public boolean onCreateOptionsMenu(Menu menu) {
62         // Inflate the menu; this adds items to the action bar if it is present.
63         getMenuInflater().inflate(R.menu.main, menu);
64         return true;
65     }
66     
67 }

最后,注意,因为我们的操作涉及到了sd卡的写入和读取权限,所以要在manifest文件中添加相应的授权信息

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

 
原文地址:https://www.cnblogs.com/Smart-Du/p/4307446.html