android数据存储之文件存储

package com.android.saveData;

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.app.Activity;
import android.content.Context;
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.Toast;

public class FileSaveDataActivity extends Activity implements OnClickListener {
    
	private EditText mEditText;
	private Button mSaveToFileButton;
	private Button mReadFromFileButton;
	private Button mSaveToSDButton;
	private Button mReadFromSDButton;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        initView();
        
        addListener();
    }
    
    private void initView() {
    	mEditText = (EditText)findViewById(R.id.mEditText_id);
    	mSaveToFileButton = (Button)findViewById(R.id.saveToFile_id);
    	mReadFromFileButton = (Button)findViewById(R.id.readFromFile_id);
    	mSaveToSDButton = (Button)findViewById(R.id.saveToSD_id);
    	mReadFromSDButton = (Button)findViewById(R.id.readFromSD_id);
    }
    
    private void addListener() {
    	mSaveToFileButton.setOnClickListener(this);
    	mReadFromFileButton.setOnClickListener(this);
    	mSaveToSDButton.setOnClickListener(this);
    	mReadFromSDButton.setOnClickListener(this);
    }

	@Override
	public void onClick(View view) {
		String fileName = "fileSave.txt";
		switch(view.getId()) {
		case R.id.readFromFile_id:
			try {
				FileInputStream inStream = getApplicationContext().openFileInput(fileName);
				ByteArrayOutputStream mStream = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int length = -1;

				while((length = inStream.read(buffer)) != -1) {
					mStream.write(buffer, 0, length);
				}
				Toast.makeText(getApplicationContext(), new String(buffer), Toast.LENGTH_LONG).show();
				mStream.close();
				inStream.close();
			} catch (FileNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			break;
		case R.id.readFromSD_id:
			if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
				File sdCardDir = Environment.getExternalStorageDirectory();
				File readFile = new File(sdCardDir, fileName);
				
			try {
				FileInputStream inStream = new FileInputStream(readFile);
				ByteArrayOutputStream mStream = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int length = -1;

				while((length = inStream.read(buffer)) != -1) {
					mStream.write(buffer, 0, length);
				}
				Toast.makeText(getApplicationContext(), new String(buffer), Toast.LENGTH_LONG).show();
				mStream.close();
				inStream.close();
			} catch (FileNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			}
			break;
		case R.id.saveToFile_id:
			try {
				FileOutputStream outStream = getApplicationContext()
												.openFileOutput(fileName, Context.MODE_WORLD_READABLE);
		
				outStream.write(mEditText.getText().toString().getBytes());
				
				outStream.close();

			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case R.id.saveToSD_id:
			
			if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
				File sdCardDir = Environment.getExternalStorageDirectory();
				File saveFile = new File(sdCardDir, fileName);
				try {
					FileOutputStream outStream = new FileOutputStream(saveFile);		
					outStream.write(mEditText.getText().toString().getBytes());
					outStream.close();
		
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
			break;
		default:
			break;
		}
	}
}
添加权限:
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
openFileOutput(fileName, Context.MODE_WORLD_READABLE)

方法,fileName不包含路径分隔符"/",如果文件不存在,android会自动创建,且保存在/data/data/<package name>/files目录,

Context.MODE_PRIVATE:该文件时私有数据,只能在应用本身访问,写入的内容会覆盖原文件,如想把新写入的内容追加到原文件,就用Context.MODE_APPEND

Context.MODE_APPEND:先检查文件是否存在,不存在就新建,存在就追加

下面两个是设置其他应用是否有权限读取这个数据:

Context.MODE_WORLD_WRITEABLE:读取数据

Context.MODE_WORLD_READABLE:写入数据

如果要其他应用要读和写权限的 可以:

openFileOutput(fileName, Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE)

Activity还提供了getCacheDir()和getFilesDir()方法:
getCacheDir()方法用于获取/data/data/<package name>/cache目录

getFilesDir()方法用于获取/data/data/<package name>/files目录

Environment.getExternalStorageState()方法用于获取SDCard的状态,如果手机装有SDCard,并且可以进行读写,那么方法返回的状态等于Environment.MEDIA_MOUNTED。

Environment.getExternalStorageDirectory()方法用于获取SDCard的目录,当然要获取SDCard的目录,你也可以这样写:

File sdCardDir = new File("/sdcard"); //获取SDCard目录

File saveFile = new File(sdCardDir, "file.txt");

//上面两句代码可以合成一句: File saveFile = new File("/sdcard/file.txt");


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值