Android在SD卡上的文件读写

该程序实现将字符串保存到文件,读取文件。

首先要获取外部存储写权限

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

 MainActivity.java

package com.example.sdfiledemo;

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

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sdfiledemo.R.id;

public class MainActivity extends Activity {

	Button write, read;
	EditText text;
	TextView lable;
	File dir, file;
	FileOutputStream fos;
	FileInputStream fis;
	ByteArrayOutputStream baos;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		write = (Button) findViewById(id.button1);
		read = (Button) findViewById(id.button2);
		text = (EditText) findViewById(id.editText1);
		lable = (TextView) findViewById(id.textView1);

		if (Environment.getExternalStorageState().equals(//查看SD卡是否挂载
				Environment.MEDIA_MOUNTED)) {
			Toast.makeText(MainActivity.this, "SD卡已挂载!", Toast.LENGTH_SHORT)
					.show();
		}

		dir = new File("/mnt/sdcard/mydir");
		file = new File(dir.toString() + "/file.txt");

		if (!dir.exists()) {// 若文件夹不存在,则创建目录
			dir.mkdirs();
			Toast.makeText(MainActivity.this, "mydir文件夹已经创建!",
					Toast.LENGTH_SHORT).show();
		}

		write.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				try {
					fos = new FileOutputStream(file, false);// 不追加
					String str = text.getText().toString();
					// 直接将字节数组写到文件中,文件若不存在会自动创建
					fos.write(str.getBytes());
					fos.close();// 关闭文件输出流

					Toast.makeText(MainActivity.this, "文件已经写入!",
							Toast.LENGTH_SHORT).show();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

		read.setOnClickListener(new OnClickListener() {

			// 将文件字节读取到字节数组输出流中,以一个字节数组作缓冲
			public void onClick(View v) {
				try {
					fis = new FileInputStream(file);
					byte[] buff = new byte[1024];// 设置一个缓冲
					baos = new ByteArrayOutputStream();
					int len;
					while ((len = fis.read(buff)) != -1) {// 如果buff没有读完
						baos.write(buff, 0, len);// 就将buff内容保存到字节数组输出流中
					}
					byte[] data = baos.toByteArray();// 得到字节数组输出流的数据
					baos.close();// 关闭字节数组输出流
					fis.close();// 关闭文件输出流

					lable.setText(new String(data));// 将读出的内容显示

					Toast.makeText(MainActivity.this, "文件已经读出!",
							Toast.LENGTH_SHORT).show();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
}

 布局文件

<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" >

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:orientation="vertical" >

        <EditText
            android:id="@+id/editText1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:ems="10" >

            <requestFocus />
        </EditText>

        <Button
            android:id="@+id/button1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/editText1"
            android:text="Button" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/linearLayout1"
            android:text="Large Text"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <Button
            android:id="@+id/button2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Button" />

    </LinearLayout>

</RelativeLayout>

 

你可能感兴趣的:(android)