Android数据存储(2)向机身内存(Internal Storage)和SDcard(External Storage)读写数据实例

总的来说向内存和SDcard中读写数据和java io操作基本差不多    而机身内存读取和SDcard读取数据有少许差别

Android开发联盟③ 433233634

机身内存数据读写

 1.机身内存读取主要用个两个类文件输入流(FileInputStream)和文件输出流(FileOutputStream): FileInputStream fileInput = this.openFileInput("test.txt") 第一个参数为 data/此程序包名/data/test.txt 文件下 的文件名 ;

FileOutputStream fileOut = this.openFileOutput("test.txt",this.MODE_APPEND)第一个参数表示文件名 第二个参数表示打开的方式  

2.获取了文件输入输出流之后 其后的文件的读写和基本的IO操作一样

SDcard数据读写

 1.SDcard数据读写需要注定的先要在Androidmainfest.xml文件中注册新建删除和读写的权限 :  

       
       
     
       

 2.读写的基本流程就是: 

   2. 1  通过Environment类的getExternalStorageState()方法来判断手机是否有SDcard:  Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)

   2.2  最通过getExternalStorageDirectory()方法来获取文件目录:File file = new File(Environment.getExternalStorageDirectory().getCanonicalPath() + "/test.txt"); 读写的文件都在sdcrad文件夹中 通过File Explorer可以导出来

   2.3 其后就和基本IO操作相同了

  2.4还有要注意一点的是 在运行的模拟器的时候要附带虚拟的SDcard时  要在Run as->Run Configurations 中要关联一下 如下图

Android数据存储(2)向机身内存(Internal Storage)和SDcard(External Storage)读写数据实例_第1张图片

机身内存数据读写实例


    
    


package com.android.xiong.fileiotest;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

	private Button read;
	private Button write;
	private EditText ed1;
	private EditText ed2;
	private EditText ed3;
	private Button delete;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		read = (Button) findViewById(R.id.read);
		write = (Button) findViewById(R.id.write);
		delete = (Button) findViewById(R.id.delete);
		ed3 = (EditText) findViewById(R.id.ed3);
		ed2 = (EditText) findViewById(R.id.ed2);
		ed1 = (EditText) findViewById(R.id.ed1);
		write.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String str = ed1.getText().toString();
				if (!str.equals("")) {
					write(str);
				}

			}
		});
		read.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				read();

			}
		});
		delete.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String str = ed3.getText().toString();
				if (!str.equals("")) {
					deleteFiles(str);
				} else {
					ed3.setText(str + ":该文件输入错误或不存在!");
				}

			}
		});

	}

	private void write(String content) {
		try {
			// 以追加的方式打开文件输出流
			FileOutputStream fileOut = this.openFileOutput("test.txt",
					this.MODE_APPEND);
			// 写入数据
			fileOut.write(content.getBytes());
			// 关闭文件输出流
			fileOut.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void read() {
		try {
			ed2.setText("");
			// 打开文件输入流
			FileInputStream fileInput = this.openFileInput("test.txt");
			BufferedReader br = new BufferedReader(new InputStreamReader(
					fileInput));
			String str = null;
			StringBuilder stb = new StringBuilder();
			while ((str = br.readLine()) !=null ) {
				stb.append(str);
			}
			ed2.setText(stb);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	//删除指定的文件
	private void deleteFiles(String fileName) {
		try {
			// 获取data文件中的所有文件列表
			List name = Arrays.asList(this.fileList());
			if (name.contains(fileName)) {
				this.deleteFile(fileName);
				ed3.setText(fileName + ":该文件成功删除!");
			} else
				ed3.setText(fileName + ":该文件输入错误或不存在!");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

SDcard数据读写实例


    
    





    
    
    
    
    

    
        
            
                

                
            
        
    

package com.android.xiong.sdcardtest;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;

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

public class MainActivity extends Activity {

	private Button write;
	private Button read;

	private EditText ed1;
	private TextView txt1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		write = (Button) findViewById(R.id.write);
		read = (Button) findViewById(R.id.read);
		ed1 = (EditText) findViewById(R.id.ed1);
		txt1 = (TextView) findViewById(R.id.txt1);
		write.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				writeSDcard(ed1.getText().toString());

			}
		});
		read.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				txt1.setText(readSDcard());
			}
		});
	}

	// 把数据写入SD卡

	private void writeSDcard(String str) {

		try {
			// 判断是否存在SD卡
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				// 获取SD卡的目录
				File file = Environment.getExternalStorageDirectory();
				FileOutputStream fileW = new FileOutputStream(file.getCanonicalPath() + "/test.txt");
				fileW.write(str.getBytes());
				fileW.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	// 从SD卡中读取数据
	private String readSDcard() {
		StringBuffer str = new StringBuffer();
		try {
			// 判断是否存在SD
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				File file = new File(Environment.getExternalStorageDirectory()
						.getCanonicalPath() + "/test.txt");                                                                
				// 判断是否存在该文件
				if (file.exists()) {
					// 打开文件输入流
					FileInputStream fileR = new FileInputStream(file);
					BufferedReader reads = new BufferedReader(
							new InputStreamReader(fileR));
					String st = null;
					while ((st =reads.readLine())!=null ) {
						str.append(st);
					}
					fileR.close();
				} else {
					txt1.setText("该目录下文件不存在");
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return str.toString();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}



你可能感兴趣的:(Android从入门到精通,Android开发之旅)